我有以下FollowingNPC
游戏对象,如果有直接视野,应该遵循Player
对象:
这里Player
对象:
BlockingLayer
和Player
层之间启用了物理碰撞:
FollowingNPC
附带有以下脚本,该脚本始终返回“未命中”结果:Raycast始终为false。这不是预期的输出,因为两个对象之间似乎都具有清晰的视图,并且可以毫无问题地绘制调试射线。
public class FollowingNPC : MonoBehaviour
{
private Vector3 heading, direction;
private float distance;
void Update()
{
heading = GameObject.FindGameObjectWithTag("Player").transform.position - transform.position;
distance = heading.magnitude;
direction = heading / distance;
RaycastHit hit;
if (Physics.Raycast(transform.position, direction, out hit))
{
if (hit.transform== GameObject.FindGameObjectWithTag("Player").transform)
{
Debug.DrawRay(transform.position, direction * distance, Color.red);
Debug.Log("Hit Player");
}
else
{
Debug.DrawRay(transform.position, direction * distance, Color.yellow);
Debug.Log("Hit Wall");
}
}
else
{
Debug.DrawRay(transform.position, direction * distance, Color.white);
Debug.Log("Not Hit");
}
}
}
请注意,在Unity中Physics
和Physics2D
是完全独立且分离的Physics引擎!
您有Rigidbody2D
和Collider2D
,所以您宁愿使用Physics2D.Raycast
!
您还应强烈避免在Physics2D.Raycast
中使用FindGameObjectWithTag
,甚至多次使用,因为它非常昂贵!宁愿once并存储结果。
Update
稍后您也应该删除所有这些// If possible and best would be to already reference it via the Inspector
[SerilaizeField] private Transform player;
// As fallback get it ONCE on runtime
private void Awake()
{
if(!player) player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
// actually those wouldn't really need to be fields
heading = player.position - transform.position;
distance = heading.magnitude;
// This line isn't really necessary
// If something I would use
//direction = heading.normalized
direction = heading / distance;
if (Physics2D.Raycast(transform.position, direction, out var hit))
{
if (hit.transform == player)
{
Debug.DrawRay(transform.position, direction * distance, Color.red);
Debug.Log("Hit Player");
}
else
{
Debug.DrawRay(transform.position, direction * distance, Color.yellow);
Debug.Log("Hit Wall");
}
}
else
{
Debug.DrawRay(transform.position, direction * distance, Color.white);
Debug.Log("Not Hit");
}
}
,因为在Debug.Log
中完成时它们也很昂贵!