Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / Items / ItemStack.cs
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using TMPro;
  4. using UnityEngine;
  5. public class ItemStack : MonoBehaviour
  6. {
  7. [SerializeField] private int itemAmount;
  8. [SerializeField] private Item item;
  9. [SerializeField] private float arcHeight = 1.5f; // Controls the height of the arc
  10. [SerializeField] private float duration = 1f; // Controls how long the arc takes
  11. private Vector3 startPosition;
  12. private Vector3 targetPosition;
  13. private GameManager gameManager;
  14. private SpriteRenderer spriteRenderer;
  15. private void Awake()
  16. {
  17. spriteRenderer = GetComponent<SpriteRenderer>();
  18. }
  19. private void Start()
  20. {
  21. gameManager = GameManager.Instance;
  22. // Set starting position as the current position
  23. startPosition = transform.position;
  24. // Calculate the target position slightly to the side of the coin, so it "flies" in an arc
  25. targetPosition = startPosition + new Vector3(1.5f, 0f, 0f); // Adjust x as needed for distance
  26. // Start the arc movement coroutine
  27. StartCoroutine(ArcMovement());
  28. }
  29. private void OnTriggerEnter2D(Collider2D collision)
  30. {
  31. if (transform.position == targetPosition)
  32. {
  33. if (collision.tag == "Player")
  34. {
  35. if (collision.GetComponentInChildren<PlayerController>().InventoryManager.AddItem(item, itemAmount))
  36. {
  37. Destroy(gameObject);
  38. }
  39. }
  40. }
  41. }
  42. public void ItemStackInit(Item item, int itemAmount)
  43. {
  44. this.item = item;
  45. this.itemAmount = itemAmount;
  46. spriteRenderer.sprite = item.ItemImage;
  47. }
  48. private IEnumerator ArcMovement()
  49. {
  50. float elapsedTime = 0f;
  51. while (elapsedTime < duration)
  52. {
  53. // Calculate progress over time
  54. float t = elapsedTime / duration;
  55. // Lerp between the start and target positions (horizontal movement)
  56. Vector3 currentPosition = Vector3.Lerp(startPosition, targetPosition, t);
  57. // Apply arc height based on a quadratic curve (creates a parabolic arc)
  58. float height = Mathf.Sin(Mathf.PI * t) * arcHeight; // `Mathf.Sin` creates the arc effect
  59. // Update the y position to follow the arc
  60. currentPosition.y += height;
  61. // Set the object's position to the current calculated position
  62. transform.position = currentPosition;
  63. // Increment elapsed time
  64. elapsedTime += Time.deltaTime;
  65. // Wait until the next frame
  66. yield return null;
  67. }
  68. // Ensure the coin ends up at the exact target position at the end
  69. transform.position = targetPosition;
  70. }
  71. }