Files
OTG_4/Assets/_Scripts/NPCInteract.cs
T
2026-06-04 19:34:38 +03:00

115 lines
3.4 KiB
C#

using UnityEngine;
[RequireComponent(typeof(SphereCollider))]
public class NPCInteract : MonoBehaviour
{
public DialogueNode startNode;
public string npcDisplayName = "Смотритель ворот";
public float interactionRadius = 3f;
public KeyCode interactKey = KeyCode.E;
public DialogueManager dialogueManager;
public Renderer highlightRenderer;
public Color highlightColor = new Color(1f, 0.78f, 0.22f, 1f);
private Transform player;
private bool playerInRange;
private Color baseColor;
private Material runtimeMaterial;
private void Awake()
{
SphereCollider trigger = GetComponent<SphereCollider>();
trigger.isTrigger = true;
trigger.radius = interactionRadius;
if (highlightRenderer == null)
highlightRenderer = GetComponentInChildren<Renderer>();
if (highlightRenderer != null)
{
runtimeMaterial = highlightRenderer.material;
baseColor = runtimeMaterial.color;
}
}
private void Start()
{
if (dialogueManager == null)
dialogueManager = DialogueManager.Instance;
SimplePlayerController controller = FindObjectOfType<SimplePlayerController>();
if (controller != null)
player = controller.transform;
}
private void Update()
{
if (player != null)
SetPlayerInRange(Vector3.Distance(transform.position, player.position) <= interactionRadius);
bool dialogueActive = dialogueManager != null && dialogueManager.IsDialogueActive;
if (!playerInRange || dialogueActive)
return;
ShowHint();
if (Input.GetKeyDown(interactKey) && startNode != null && dialogueManager != null)
dialogueManager.StartDialogue(startNode, npcDisplayName);
}
private void OnTriggerEnter(Collider other)
{
if (other.GetComponentInParent<SimplePlayerController>() != null)
{
player = other.transform;
SetPlayerInRange(true);
}
}
private void OnTriggerExit(Collider other)
{
if (other.GetComponentInParent<SimplePlayerController>() != null)
SetPlayerInRange(false);
}
private void OnDrawGizmosSelected()
{
Gizmos.color = new Color(1f, 0.75f, 0.2f, 0.25f);
Gizmos.DrawSphere(transform.position, interactionRadius);
Gizmos.color = new Color(1f, 0.75f, 0.2f, 1f);
Gizmos.DrawWireSphere(transform.position, interactionRadius);
}
private void SetPlayerInRange(bool inRange)
{
if (playerInRange == inRange)
return;
playerInRange = inRange;
SetHighlight(inRange);
if (!inRange && DialogueHUD.Instance != null)
DialogueHUD.Instance.HideHint();
}
private void SetHighlight(bool enabled)
{
if (runtimeMaterial == null)
return;
runtimeMaterial.color = enabled ? highlightColor : baseColor;
}
private void ShowHint()
{
if (DialogueHUD.Instance != null)
DialogueHUD.Instance.ShowHint("Нажмите E для разговора");
else if (dialogueManager != null && dialogueManager.hintText != null)
{
dialogueManager.hintText.text = "Нажмите E для разговора";
dialogueManager.hintText.gameObject.SetActive(true);
}
}
}