using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; [RequireComponent(typeof(MovementBehaviour))] public class InteractionBehaviour : MonoBehaviour, IObjectParentHolder { // Start is called before the first frame update private MovementBehaviour _movementBehaviour; [SerializeField] private float _interactionDistance = 2.0f; [SerializeField] private LayerMask _interactionLayer; private GameObject _lastInteractedObject = null; public event EventHandler OnSelectedCounter; [SerializeField] private Transform _holdItemTransform; private Object _heldObject; public class OnSelectedCounterArgs : EventArgs { public GameObject selectedCounter; } void Start() { } void Awake() { _movementBehaviour = GetComponent(); } // Update is called once per frame void Update() { } public void HandleInteraction() { Vector2 inputVector = _movementBehaviour.desiredMovementDirection.normalized; Vector3 moveDirection = new Vector3(inputVector.x, 0, inputVector.y); Vector3 origin = transform.position; origin.y += 0.5f; //slight offset so we dont go under the counters RaycastHit hit; Debug.DrawRay(origin, transform.forward * _interactionDistance, Color.red); if (Physics.Raycast(origin, transform.forward, out hit, _interactionDistance, _interactionLayer)) { GameObject hitObject = hit.transform.gameObject; //Check if the object has a component that has the IInteractable interface if (hitObject.TryGetComponent(out IInteractable interactable)) { if(_lastInteractedObject != hitObject) { setSelectedObject(hitObject); } } else { setSelectedObject(null); } } else { setSelectedObject(null); } } public void Interact() { if (_lastInteractedObject == null) return; if (_lastInteractedObject.TryGetComponent(out IInteractable interactable)) { interactable.Interact(this); } } private void setSelectedObject(GameObject selectedCounter) { _lastInteractedObject = selectedCounter; OnSelectedCounter?.Invoke(this, new OnSelectedCounterArgs { selectedCounter = _lastInteractedObject }); } public Transform GetHolderTransform() { return _holdItemTransform; } public void SetObject(Object obj) { _heldObject = obj; } public Object GetObject() { return _heldObject; } public void ClearObject() { _heldObject = null; } public bool HasObject() { return _heldObject != null; } }