miepzerino
2025-04-08 40ac185dc7a017d95771fe580c77eab20e663908
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Interactable.cs - Base abstract class for all interactable objects
using UnityEngine;
using UnityEngine.Events;
 
public abstract class Interactable : MonoBehaviour
{
    [SerializeField] private string promptMessage = "Press E to interact";
    [SerializeField] private float interactionDistance = 3f;
 
    // Event that will be triggered when the player interacts with this object
    public UnityEvent OnInteract = new UnityEvent();
 
    // Each derived class must implement how it processes interaction
    public abstract void Interact();
 
    // Returns the prompt message for UI display
    public string GetPromptMessage()
    {
        return promptMessage;
    }
 
    // Check if player is within interaction distance
    public bool IsInRange(Transform playerTransform)
    {
        float distance = Vector3.Distance(transform.position, playerTransform.position);
        return distance <= interactionDistance;
    }
 
    // Optional: Visualize interaction range in editor
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, interactionDistance);
    }
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            // Player entered trigger zone
            PlayerInteraction playerInteraction = other.GetComponent<PlayerInteraction>();
            if (playerInteraction != null)
            {
                playerInteraction.SetCurrentInteractable(this);
            }
        }
    }
 
    protected void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            // Player exited trigger zone
            PlayerInteraction playerInteraction = other.GetComponent<PlayerInteraction>();
            if (playerInteraction != null)
            {
                playerInteraction.SetCurrentInteractable(null);
            }
        }
    }
}