Last active
February 23, 2017 06:28
-
-
Save Domiii/cf44ded5c406c8521886e04cb4630177 to your computer and use it in GitHub Desktop.
[Unity v5.4] Let's Player pick up an object and then lets it hover over their head
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
/// <summary> | |
/// Halo (光環) | |
/// </summary> | |
public class HaloPickUp2D : MonoBehaviour { | |
public Player player; | |
public Vector2 relativePosition = new Vector2(0, 1); | |
public Vector2 bobbingRadius = new Vector2(0.8f, 0.2f); | |
public float bobbingSpeed = 1f; | |
Vector2 startPos; | |
public bool IsEquipped { | |
get { | |
return player != null; | |
} | |
} | |
void Start() { | |
startPos = transform.position; | |
} | |
void Update() { | |
if (IsEquipped) { | |
Hover (); | |
if (Input.GetKeyDown (KeyCode.DownArrow)) { | |
Unequip (); | |
} | |
} | |
} | |
void Hover() { | |
var pos = player.transform.position + (Vector3)relativePosition; | |
var theta = Time.time * 2 * Mathf.PI * bobbingSpeed; | |
pos.x += Mathf.Sin(theta) * bobbingRadius.x; | |
pos.y += Mathf.Cos(theta) * bobbingRadius.y; | |
transform.position = pos; | |
} | |
void OnTriggerEnter2D(Collider2D other) { | |
if (IsEquipped) { | |
// don't do anything when already equipped | |
return; | |
} | |
var triggerPlayer = other.GetComponentInParent<Player> (); | |
if (triggerPlayer != null) { | |
Equip (triggerPlayer); | |
} | |
} | |
void Equip(Player triggerPlayer) { | |
player = triggerPlayer; | |
transform.localScale /= 2; | |
} | |
/// <summary> | |
/// Player dropped (放下) the halo | |
/// </summary> | |
void Unequip() { | |
transform.localScale *= 2; | |
player = null; | |
transform.position = startPos; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment