Files
Crash-Course/Assets/Scripts/Player/UseItem.cs

64 lines
2.0 KiB
C#
Raw Normal View History

2025-02-17 19:02:14 -05:00
using UnityEngine;
public class UseItem : MonoBehaviour
{
2025-03-17 18:20:03 -04:00
[SerializeField] private string itemTag;
private GameObject heldItem;
private bool isHoldingItem = false;
2025-03-20 14:45:29 -04:00
private float holdStartTime;
2025-03-28 13:00:37 -04:00
public float holdTime;
void Update()
2025-02-17 19:02:14 -05:00
{
if (isHoldingItem)
{
// Keeps hat on the player's head
2025-03-17 18:20:03 -04:00
heldItem.transform.position = transform.position + Vector3.up;
2025-03-20 14:45:29 -04:00
if (GameManager.gameMode == GameManager.GameMode.keepAway)
{
// Adds time to the player's leaderboard standing
2025-03-28 13:00:37 -04:00
holdTime += Time.deltaTime;
2025-03-25 22:21:21 -04:00
GameManager.Instance.UpdatePlayerHoldTime(gameObject, holdTime);
2025-03-20 14:45:29 -04:00
}
}
2025-02-17 19:02:14 -05:00
}
private void OnCollisionEnter2D(Collision2D collision) // Player automatically picks up hat when touching it
{
2025-03-17 18:20:03 -04:00
if (collision.gameObject.CompareTag("Hat") && !isHoldingItem)
{
PickUpItem(collision.gameObject);
}
}
private void PickUpItem(GameObject item) // Player picks up hat and starts hold counter
{
heldItem = item;
isHoldingItem = true;
2025-03-20 14:45:29 -04:00
holdStartTime = Time.time;
item.GetComponent<Collider2D>().enabled = false;
2025-03-17 18:20:03 -04:00
item.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
item.transform.rotation = Quaternion.identity;
2025-03-20 14:45:29 -04:00
if (!GameManager.playerHoldTimes.ContainsKey(gameObject))
{
GameManager.playerHoldTimes[gameObject] = 0f;
}
}
public void DropItem() // Player drops hat when hit
{
if (isHoldingItem)
{
heldItem.GetComponent<Collider2D>().enabled = true;
2025-03-17 18:20:03 -04:00
heldItem.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
2025-03-17 19:59:41 -04:00
heldItem.transform.position += Vector3.up * 3f;
heldItem = null;
isHoldingItem = false;
2025-03-20 14:45:29 -04:00
if (GameManager.playerHoldTimes.ContainsKey(gameObject))
{
GameManager.playerHoldTimes.Remove(gameObject);
}
}
}
2025-02-17 19:02:14 -05:00
}