_xiaofang/xiaofang/Assets/Script/Character/Skills/Skill_watering.cs
2024-10-21 10:08:49 +08:00

78 lines
2.3 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Skill_watering : MonoBehaviour
{
private CharacterAin CharacterAin;
public float detectionRadius = 10f; // 检测火源的范围
public LayerMask fireLayerMask; // 用于检测的火层
// Start is called before the first frame update
void Start()
{
CharacterAin = transform.GetComponent<CharacterAin>();
}
/// <summary>
/// 开始洒水
/// </summary>
/// <param name="currentItem">需要一个物体</param>
public void StartWatering(GameObject currentItem)
{
CharacterAin.SetSkillAin(CharacterSkill.Watering);
// 检测附近的火源并调整角色朝向
DetectAndLookAtFire();
if (currentItem.GetComponent<NoFire>() != null)
{
currentItem.GetComponent<NoFire>().StartFire();
}
}
/// <summary>
/// 结束洒水
/// </summary>
/// <param name="currentItem">一个物体</param>
public void StopWatering(GameObject currentItem)
{
CharacterAin.SetSkillAin(CharacterSkill.NoSkill);
if (currentItem.GetComponent<NoFire>() != null)
{
currentItem.GetComponent<NoFire>().StopFire();
}
}
/// <summary>
/// 检测周围的火源,并让角色朝向最近的火源
/// </summary>
private void DetectAndLookAtFire()
{
Collider[] objectsInRange = Physics.OverlapSphere(transform.position, detectionRadius, fireLayerMask);
// 遍历范围内的所有对象,查找标签为 "fire" 的对象
Collider nearestFire = null;
float minDistance = Mathf.Infinity;
foreach (Collider obj in objectsInRange)
{
if (obj.CompareTag("fire")) // 如果对象的标签是 "fire"
{
float distance = Vector3.Distance(transform.position, obj.transform.position);
if (distance < minDistance)
{
nearestFire = obj;
minDistance = distance;
}
}
}
// 如果找到了最近的火源,让角色朝向它
if (nearestFire != null)
{
Vector3 directionToFire = (nearestFire.transform.position - transform.position).normalized;
directionToFire.y = 0; // 保持角色在水平方向上朝向火源
transform.forward = directionToFire;
}
}
}