Skip to content

Instantly share code, notes, and snippets.

@Domiii
Last active February 23, 2017 06:28
Show Gist options
  • Save Domiii/cf44ded5c406c8521886e04cb4630177 to your computer and use it in GitHub Desktop.
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
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