Hệ thống Tương tác theo Ngữ cảnh
C# Code
/* --- IInteractable.cs (Interface) --- */
public interface IInteractable
{
void Interact();
string GetInteractText();
}
/* --- PlayerInteraction.cs (Gắn vào Player) --- */
using UnityEngine;
using TMPro;
public class PlayerInteraction : MonoBehaviour
{
public Camera playerCamera;
public float interactionDistance = 3f;
public TextMeshProUGUI interactionText;
private IInteractable currentInteractable;
void Update()
{
RaycastHit hit;
bool hasHit = Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, interactionDistance);
if (hasHit && hit.collider.GetComponent<IInteractable>() != null)
{
currentInteractable = hit.collider.GetComponent<IInteractable>();
interactionText.text = currentInteractable.GetInteractText();
interactionText.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.E))
{
currentInteractable.Interact();
}
}
else
{
currentInteractable = null;
interactionText.gameObject.SetActive(false);
}
}
}
/* --- Door.cs (Ví dụ vật tương tác) --- */
using UnityEngine;
public class Door : MonoBehaviour, IInteractable
{
private bool isOpen = false;
public string GetInteractText()
{
return isOpen ? "Press E to Close Door" : "Press E to Open Door";
}
public void Interact()
{
isOpen = !isOpen;
Debug.Log(isOpen ? "Door Opened" : "Door Closed");
// Thêm logic animation mở/đóng cửa ở đây
}
}Một hệ thống cho phép người chơi tương tác với nhiều loại đối tượng (cửa, NPC, vật phẩm) chỉ bằng một nút bấm khi ở trong tầm.