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

public class ItemStack : MonoBehaviour
{
    [SerializeField] private int itemAmount;
    [SerializeField] private Item item;
    [SerializeField] private float arcHeight = 1.5f;  // Controls the height of the arc
    [SerializeField] private float duration = 1f;   // Controls how long the arc takes
    private Vector3 startPosition;
    private Vector3 targetPosition;

    private GameManager gameManager;
    private SpriteRenderer spriteRenderer;

    private void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    private void Start()
    {
        gameManager = GameManager.Instance;

        // 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(1.5f, 0f, 0f);  // Adjust x as needed for distance

        // Start the arc movement coroutine
        StartCoroutine(ArcMovement());
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (transform.position == targetPosition)
        {
            if (collision.tag == "Player")
            {
                if (collision.GetComponentInChildren<PlayerController>().InventoryManager.AddItem(item, itemAmount))
                {
                    Destroy(gameObject);
                }
            }
        }
    }

    public void ItemStackInit(Item item, int itemAmount)
    {
        this.item = item;
        this.itemAmount = itemAmount;
        spriteRenderer.sprite = item.ItemImage;
    }


    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;
    }
}