Unity - raycast is clearly colliding but does not work?

血红的双手。 提交于 2021-01-05 11:06:23

问题


Ok I have 2 objects on the Default layer that I need to trigger a jump with when raycast collides. I can see that the raycast is intersecting the platform:

And here is my collider on the platform:

And yet nothing is printed with:

Vector3 rotation = transform.forward;

        RaycastHit hit;
        Debug.DrawRay(new Vector3(transform.position.x, transform.position.y + 0.4f, transform.position.z), rotation, Color.green);
        if (Physics.Raycast(new Vector3(transform.position.x, transform.position.y + 0.4f, transform.position.z), rotation, out hit, rayDistance))
        {
            print(hit.transform);
            if (hit.transform.GetComponent<Platform>() != null)
            {
                Jump(hit.transform);
            }
        }

What is wrong here?


回答1:


Try this code adapted from https://docs.unity3d.com/ScriptReference/Physics.Raycast.html using your values:

RaycastHit hit;
Vector3 startPoint = new Vector3(transform.position.x, transform.position.y + 0.4f, transform.position.z);
if (Physics.Raycast(startPoint, rotation, out hit, Mathf.Infinity))
{
    Debug.DrawRay(startPoint, rotation * hit.distance, Color.yellow);
    Debug.Log("Did Hit");
}
else
{
    Debug.DrawRay(startPoint, rotation * 1000, Color.white);
    Debug.Log("Did not Hit");
}

Here it is a GIF from a test I did.

This is just a test to see if the problem is the difference between ray distances.

You may also use Debug.DrawLine instead and then set up the end point with the same distance used in the RayCast.

Vector3 startPoint = new Vector3(transform.position.x, transform.position.y + 0.4f, transform.position.z);
if (Physics.Raycast(startPoint, rotation, out hit, rayDistance))
{
    Debug.DrawLine(startPoint, startPoint + rotation * rayDistance, Color.green);
}
else Debug.DrawLine(startPoint, startPoint + rotation * rayDistance, Color.red);

Another GIF using this code.

If it still doesn't work, try checking out the matrix collision.

Don't forget that you may also use a layermask in your raycast. :)



来源:https://stackoverflow.com/questions/55073121/unity-raycast-is-clearly-colliding-but-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!