Files
TopDown/Assets/Scripts/CartInteractable.cs
2026-08-05 08:18:15 +01:00

62 lines
2.0 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.Events;
namespace Interactions
{
public class CartInteractable : Interactable
{
[Header("Cart Roll Settings")]
[Tooltip("The direction the cart will roll when interacted with.")]
[SerializeField] private Vector3 rollDirection = Vector3.forward;
[Tooltip("How far the cart rolls.")]
[SerializeField] private float rollDistance = 5.0f;
[Tooltip("Speed/Duration of the roll movement.")]
[SerializeField] private float rollSpeed = 3.0f;
[Tooltip("If true, can only be rolled once.")]
[SerializeField] private bool rollOnce = true;
[Header("Events")]
[SerializeField] private UnityEvent onRollStart;
[SerializeField] private UnityEvent onRollComplete;
private bool hasRolled = false;
private bool isRolling = false;
public override void Interact(GameObject interactor)
{
if (isRolling || (hasRolled && rollOnce)) return;
base.Interact(interactor);
StartCoroutine(RollCartRoutine());
}
private IEnumerator RollCartRoutine()
{
isRolling = true;
onRollStart?.Invoke();
Vector3 startPosition = transform.position;
// Roll in world or local direction space
Vector3 worldRollDir = transform.TransformDirection(rollDirection.normalized);
Vector3 targetPosition = startPosition + (worldRollDir * rollDistance);
while (Vector3.Distance(transform.position, targetPosition) > 0.05f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, rollSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPosition;
isRolling = false;
hasRolled = true;
onRollComplete?.Invoke();
Debug.Log($"[CartInteractable] Cart finished rolling to {targetPosition}");
}
}
}