有人可以帮我吗?我正在使用下面的代码尝试让敌人看一下他是否可以看到玩家。
但是问题是当我在墙后时他还能看到我吗 有人可以帮我吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
public class Test : MonoBehaviour
{
[SerializeField]
float distance;
public GameObject player;
public Transform Shootpoint;
public bool CanSee = false;
[SerializeField]
float chaseDistence = 0.5f;
void Update()
{
distance = Vector3.Distance(Shootpoint.position, player.transform.position);
if (!Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
{
Debug.DrawLine(Shootpoint.position, player.transform.position, Color.red);
CanSee = false;
Debug.Log("CANT SEE");
}
else if (Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
{
Debug.DrawLine(Shootpoint.position, player.transform.position, Color.green);
CanSee = true;
Debug.Log("CAN SEE");
}
}
}
答案 0 :(得分:3)
就像提到的@BugFinder一样,您只是在检查RayCast
是否与某物发生了碰撞,而不一定是玩家。
如果要确定射线是否仅与播放器碰撞,而不与其他对象碰撞,请使用设置RaycastHit
对象的函数重载。然后,您可以获得tag
并将其与播放器的标签进行比较。 (请参见Physics.RayCast和RaycastHit)
您可以这样实现:
RaycastHit hitInfo;
if(Physics.Raycast(Shootpoint.position, player.transform.position, out hitInfo, chaseDistence))
{
if (hitInfo.collider.CompareTag("player"))
{
// Can see
}
else
{
// Can't see, raycast hit something
}
}
else
{
// Can't see, raycast hit nothing
}