如下图所示,当物体B在A前前方45°角范围内,并且A、B之间距离五米,输出 有敌人入侵!
代码展示
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lesson6_LianXi : MonoBehaviour
{
public Transform target;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float dotResult = Vector3.Dot(this.transform.forward, (target.position - this.transform.position).normalized);
// 2.用反三角函数得出角度
float JiaoDu = Mathf.Acos(dotResult) * Mathf.Rad2Deg;
// AB之间的距离
float JvLi = Vector3.Distance(this.transform.position, target.position);
// 为什么小于22.5?因为我们要实现的是前方45°角,即物体和检测的物体两边的夹角加起来等于45°,所以要小于22.5°
if (JiaoDu <= 22.5f && JvLi <= 5)
{
print("发现敌人入侵!");
}
}
}
不要忘记在unity Inspector界面将目标物体拖进去