Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / Items / Coin.cs
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class Coin : MonoBehaviour
{
    [SerializeField] private GameObject pickGoldPrefab;
    [SerializeField] private int value;
    [SerializeField] private float arcHeight = 2f;  // Controls the height of the arc
    [SerializeField] private float duration = 1f;   // Controls how long the arc takes
    private Vector3 startPosition;
    private Vector3 targetPosition;
    private Transform canvasTransform;

    private void Awake()
    {
    }

    private void Start()
    {
        // Set starting position as the current position
        startPosition = transform.position;

        // Calculate the target position slightly to the side of the coin, so it "flies" in an arc
        targetPosition = startPosition + new Vector3(2f, 0f, 0f);  // Adjust x as needed for distance

        // Start the arc movement coroutine
        StartCoroutine(ArcMovement());
        canvasTransform = GameObject.Find("WorldUI").transform;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag ==  "Player")
        {
            GameManager.Instance.PlayerGold += value;
            GameObject obj = Instantiate(pickGoldPrefab, gameObject.transform.position, Quaternion.identity, canvasTransform);

            TextMeshProUGUI tmp = obj.GetComponentInChildren<TextMeshProUGUI>();
            if (tmp != null)
            {
                tmp.text = value.ToString();
            }

            Destroy(gameObject);
        }
    }

    private IEnumerator ArcMovement()
    {
        float elapsedTime = 0f;
        while (elapsedTime < duration)
        {
            // Calculate progress over time
            float t = elapsedTime / duration;

            // Lerp between the start and target positions (horizontal movement)
            Vector3 currentPosition = Vector3.Lerp(startPosition, targetPosition, t);

            // Apply arc height based on a quadratic curve (creates a parabolic arc)
            float height = Mathf.Sin(Mathf.PI * t) * arcHeight;  // `Mathf.Sin` creates the arc effect

            // Update the y position to follow the arc
            currentPosition.y += height;

            // Set the object's position to the current calculated position
            transform.position = currentPosition;

            // Increment elapsed time
            elapsedTime += Time.deltaTime;

            // Wait until the next frame
            yield return null;
        }

        // Ensure the coin ends up at the exact target position at the end
        transform.position = targetPosition;
    }
}