81 lines
2.9 KiB
C#
81 lines
2.9 KiB
C#
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
using System.Collections;
|
|
using Hallucinate.Audio;
|
|
using Hallucinate.AI;
|
|
|
|
public class GerminiNPC : MonoBehaviour
|
|
{
|
|
[SerializeField]
|
|
private string npcPersona =
|
|
"Ngươi là một lão thợ rèn cọc cằn tên là Tom, ngươi rất ghét những kẻ mang phế liệu đến tiệm của mình. Chỉ trả lời ngắn gọn trong 2 câu, theo phong cách trung cổ.";
|
|
|
|
public string playerHeldItem = "Thanh kiếm rỉ sét";
|
|
public float interactionDistance = 5f; // Khoảng cách tối đa để nói chuyện
|
|
public Transform playerTransform; // Gán transform của Player vào đây
|
|
|
|
[Header("Audio")]
|
|
public string startTalkSound = "NPC_Interact";
|
|
public string responseSound = "NPC_Response";
|
|
|
|
private void Update()
|
|
{
|
|
if (Keyboard.current != null && Keyboard.current.fKey.wasPressedThisFrame)
|
|
{
|
|
if (CanSeePlayer())
|
|
{
|
|
AudioManager.Instance?.Play(startTalkSound, position: transform.position);
|
|
StartCoroutine(GetGerminiReponse());
|
|
}
|
|
else
|
|
{
|
|
Debug.Log("<color=yellow>Hệ thống:</color> Bạn ở quá xa hoặc bị tường che khuất!");
|
|
}
|
|
}
|
|
}
|
|
|
|
private bool CanSeePlayer()
|
|
{
|
|
if (playerTransform == null)
|
|
{
|
|
// Tự tìm player nếu chưa gán
|
|
GameObject player = GameObject.FindGameObjectWithTag("Player");
|
|
if (player != null) playerTransform = player.transform;
|
|
else return false;
|
|
}
|
|
|
|
// 1. Check khoảng cách
|
|
float dist = Vector3.Distance(transform.position, playerTransform.position);
|
|
if (dist > interactionDistance) return false;
|
|
|
|
// 2. Check xem có bị tường che không (Raycast)
|
|
Vector3 direction = (playerTransform.position + Vector3.up) - (transform.position + Vector3.up);
|
|
RaycastHit hit;
|
|
if (Physics.Raycast(transform.position + Vector3.up, direction, out hit, interactionDistance))
|
|
{
|
|
if (hit.collider.CompareTag("Player") || hit.collider.transform.IsChildOf(playerTransform))
|
|
{
|
|
return true; // Thấy đầu/người player
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private IEnumerator GetGerminiReponse()
|
|
{
|
|
string prompt = $"Ta muốn bán cho ông món đồ này: {playerHeldItem}";
|
|
|
|
Hallucinate.AI.GeminiService.Instance.GetResponse(npcPersona, prompt, (response) => {
|
|
Debug.Log($"<color=green>Tom:</color> {response}");
|
|
AudioManager.Instance?.Play(responseSound, position: transform.position);
|
|
|
|
// Nếu có ChatBubble gắn kèm thì hiển thị luôn
|
|
var bubble = GetComponentInChildren<Hallucinate.UI.ChatBubble>(true);
|
|
if (bubble != null) bubble.Show(response);
|
|
});
|
|
|
|
yield break;
|
|
}
|
|
}
|