unity3d Unity RayCast确实击中了物体,但它没有显示在场景视图或游戏视图中

hk8txs48  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(208)

我最近刚开始使用Unity,但遇到了光线投射的问题。我的代码似乎可以工作,因为控制台给了我立方体被击中的信息,但它没有在场景视图或游戏视图中显示光线。我使用的脚本如下:

public class RayCast : MonoBehaviour
{
    Ray ray;
    public LayerMask layersToHit;

    void Start()
    {
        ray = new Ray(transform.position, transform.forward);
        Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue);

        CheckForColliders();
    }

    void CheckForColliders()
    {
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            Debug.Log(hit.collider.gameObject.name + " was hit ");
            Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);
        }
    }
}

现在我也选择了在Unity中的LayersToHit来点击连接到小立方体的连接器。在屏幕上绘制光线的代码有什么问题吗?或者我需要在设置中更改任何东西吗?提前感谢!
编辑:新代码:

public class RayCast : MonoBehaviour
{
    private Ray ray;
    public LayerMask layersToHit;

    void Start()
    {
        ray = new Ray(transform.position, transform.forward);
        //Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue);
        CheckForColliders();
    }

    void CheckForColliders()
    {
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            Debug.Log(hit.collider.gameObject.name + " was hit ");
            //Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);

        }
    }
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawRay(ray.origin, ray.direction * 100f);
    }
}
qacovj5a

qacovj5a1#

我测试了你的代码,它在我的计算机上运行正常。所以我认为问题可能出在设置上。解释:

void Start()
{
    ray = new Ray(transform.position, transform.forward);

    /* Here you are drawing the first ray, you did not have a duration set
    for this one */
    Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue, 10f);

    CheckForColliders();
}

void CheckForColliders()
{
    if (Physics.Raycast(ray, out RaycastHit hit))
    {
        Debug.Log(hit.collider.gameObject.name + " was hit ");

        // Here you are drawing the line again.
        Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);
    }
}

这段代码运行良好,但我不确定你是否打算画两次线,我推测问题是我下面描述的一个,在下面的链接中有一个图像,显示了你可能没有启用的设置,也显示了正在画的线。
Check if the draw Gizmos button on the top right of the scene view window is enabled.
另外,如果你想在不运行游戏的情况下看到射线,你的代码应该如下所示:

private Ray ray;
public LayerMask layersToHit;

void Start()
{
    ray = new Ray(transform.position, transform.forward);
    //Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue);
    CheckForColliders();
}

void CheckForColliders()
{
    if (Physics.Raycast(ray, out RaycastHit hit))
    {
        Debug.Log(hit.collider.gameObject.name + " was hit ");
        //Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);

    }
}
private void OnDrawGizmos()
{
    ray = new Ray(transform.position, transform.foward);
    Gizmos.color= Color.red;
    Gizmos.DrawRay(ray.origin, ray.direction * 100f);
}

相关问题