问题
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