Raycast仅会返回false,即使预期为true

问题描述 投票:0回答:1

我有以下FollowingNPC游戏对象,如果有直接视野,应该遵循Player对象:

FollowingNPC

这里Player对象:

Player

BlockingLayerPlayer层之间启用了物理碰撞:

Collision Matrix

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");
        }
    }
}
unity3d
1个回答
0
投票

请注意,在Unity中PhysicsPhysics2D是完全独立且分离的Physics引擎!

您有Rigidbody2DCollider2D,所以您宁愿使用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中完成时它们也很昂贵!

© www.soinside.com 2019 - 2024. All rights reserved.