# 怪物AI之发现玩家（视觉范围发现系列）

1.碰撞器R范围检测。
2.地图分块范围检测。

private bool Find(GameObject _Monster)
{
Vector3 otherPos = _Monster.gameObject.transform.position;
v = transform.position - otherPos;
v.y = 0.5f; //处理一下y轴，因为判断建立在二维上
w = _Monster.gameObject.GetComponent<FindPlayerAI>().getFace() - otherPos;
w.y = 0.5f;
if (Vector3.Angle(v, w) < 30)
{
return true;
}
return false;
}

PS：如果想在三维上进行判断的话，同理在处理一下yz轴平面就ok了。

void OnTriggerEnter(Collider other)
{
if (!other.name.Equals("Terrain"))
{
if (Find(other.gameObject)) //接上一个Find代码
{
Debug.Log("发现");
}
}
}

Map.cs：

public class Map : MonoBehaviour{

private static Map _Instance;

public static Map Instance
{
get
{
if (_Instance == null)
{
}
return _Instance;
}
}

private int PlayerPos = -1;

private GameObject[][] Monster = new GameObject[100][];
private int[] MonsterNum = new int[100];

//public int n = 0;

void Awake()
{
for (int i = 0; i < 100; i++)
{
Monster[i] = new GameObject[10];
MonsterNum[i] = 0;
}
}

int getPos(GameObject go)
{
float x = go.transform.position.x;
float z = go.transform.position.z;
x /= 20;
z /= 20;
int pos = (int)(Mathf.Floor(x) + Mathf.Floor(z) * 10);
return pos;
}

public void setMonsterPos(GameObject _Monster)
{
int pos = getPos(_Monster);
Monster[pos][MonsterNum[pos]++] = _Monster;
Debug.Log(pos + _Monster.name);
}

public int getPlayerPos(GameObject _Player)
{
int pos = getPos(_Player);
if (PlayerPos == pos)
{
return -1;
}
else
{
PlayerPos = pos;
}
return pos;
}

public GameObject[] getMonster(int pos)
{
return Monster[pos];
}

}

public class PlayerAI : MonoBehaviour {

Vector3 v;
Vector3 w;
Vector3 otherPos;
GameObject[] Monster = new GameObject[10];

private bool Find(GameObject _Monster)
{
otherPos = _Monster.gameObject.transform.position;
v = transform.position - otherPos;
v.y = 0.5f;
w = _Monster.gameObject.GetComponent<MonsterAI>().getFace() - otherPos;
w.y = 0.5f;
if (Vector3.Angle(v, w) < 30)
{
return true;
}
return false;
}

//void OnTriggerEnter(Collider other)
//{
//    if (!other.name.Equals("Terrain"))
//    {
//        if (Find(other.gameObject))
//        {
//            Debug.Log("发现");
//        }
//    }
//}

void Update()
{
int pos = Map.Instance.getPlayerPos(gameObject);
if (pos != -1)
{
Monster = Map.Instance.getMonster(pos);
}
for (int i = 0; i < Monster.Length; i++)
{
if (Monster[i] != null)
{
if (Find(Monster[i]))
{
Debug.Log(i + "发现");
}
}
}
}
}

public class MonsterAI : MonoBehaviour {

public GameObject Player;

private Vector3 Face;

void Start () {
Face = transform.position + transform.rotation * Vector3.forward * 10;
Map.Instance.setMonsterPos(gameObject);
}

public Vector3 getFace()
{
return Face;
}

void Update()
{
Face = transform.position + transform.rotation * Vector3.forward * 10;
//Debug.DrawLine(transform.position, Face, Color.red);
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120