首页 > 解决方案 > Physics.Raycast 似乎无法始终如一地工作

问题描述

在此处输入图像描述

我正在研究基于光线投射的寻路系统。基本上我要做的是在对象周围生成点/检查该对象是否可以到达这些点,并检查这些点是否可以到达目标。目标是照片背面的绿色圆柱体。这是我的图层蒙版,它基本上说将玩家作为对撞机/障碍物忽略:

layerMask = Physics.DefaultRaycastLayers & ~(1 << 3);

这是我的光线投射代码:

    // Check if enemy can see player without any obstructions
    bool CanSeeDestination(Vector3 startingPoint, Vector3 destination)
    {
        if(Physics.Raycast(startingPoint, destination, 50f, layerMask))
        {
            Debug.DrawLine(startingPoint, destination, Color.red);
            return false;
        } else
        {
            Debug.DrawLine(startingPoint, destination, Color.green);
            return true;
        }
    }

最后是我的寻路功能:

    // Raycast based pathfinding
    void Pathfind()
    {
        List<Vector3> surroundingPoints = new List<Vector3>();

        bool foundTarget = false;

        // Nested loop to build surrounding points vector array
        for(var i = 1; i <= 10; i++)
        {
            for(var k = 1; k <= 10; k++)
            {
                // Offset by half of max to get negative distance
                int offsetI = i - 5;
                int offsetK = k - 5;

                surroundingPoints.Add(new Vector3(transform.localPosition.x + offsetI, stepOverHeight.y, transform.localPosition.z + offsetK));
            }
        }



        // Loop through array of surrounding vectors
        for(var m = 0; m < surroundingPoints.Count; m++)
        {
            // If enemy can reach this surrounding point and this surrounding point has an unobstructed path to the target
            if(CanSeeDestination(transform.localPosition, surroundingPoints[m]) && CanSeeDestination(surroundingPoints[m], player.transform.position))
            {
                float distanceFromEnemyToTarget = Vector3.Distance(transform.position, surroundingPoints[m]);
                float distanceFromTargetToPlayer = Vector3.Distance(surroundingPoints[m], player.transform.position);
                float totalDistance = distanceFromEnemyToTarget + distanceFromTargetToPlayer;

                // If this total path distance is shorter than current path distance set this as target
                if(totalDistance < currentPathDistance)
                {
                    currentPathDistance = totalDistance;
                    target = surroundingPoints[m];
                    foundTarget = true;
                }
            }
        }

        if (!foundTarget)
        {
            target = transform.position;
        }
        
    }

由于某种原因,光线投射在障碍物的右侧而不是左侧触发。此外,如果我增加障碍物大小或对撞机大小,我最终可以挡住左侧。不知道为什么左边的光线投射是绿色的并且仍然通过对撞机。

标签: unity3dgame-physicsraycastingmesh-collider

解决方案


我解决了这个问题。问题出在这一行:

    if(Physics.Raycast(startingPoint, destination, 50f, layerMask))

我应该一直在使用 Physics.Linecast 两个在两点之间。光线投射进入矢量“方向”线投射在两点之间进行。正确的代码是:

    if(Physics.Linecast(startingPoint, destination, layerMask))

推荐阅读