- Home /
Why does Physics2D.Raycast alway return true?
function IsGrounded() : boolean {
return Physics2D.Raycast(transform.position,-(Vector3.up),0.6);
}
Does anyone know why this function always returns, even when I jump higher then 0.6? The number 0.6 represents :
[ (GetComponent(BoxCollider2D).size.y) * 0.5 + 0.1 ]
Even when I jump 100+ units upwards, it still returns true. Can anyone please help me? Thanks.
Ironically, I was just working with these last night. Physics2D.Raycast was always returning a RaycastHit2d - but the hit.transform was null if it didn't hit anything.
@SirGive so did you find a solution to the problem? Is there a way to check if it returns the hit.transform ?
Answer by Patel-Sagar · Mar 26, 2014 at 11:28 AM
I think there is one big difference between 2D collider and 3D collider in case of Raycast. 3D colliders are one sided(sphere/Cube is not detected if you raycast from its center). in case of 2D box colliders, it is detected even if ray's origin is its center.
To avoid this situation, always add bounds to origin of ray. for example, your object is at (0,0,0) with scale (1,1,1). then Physics2D.Raycast(transform.position - new vector3(0,transform.localscale.y/2,0),-(Vector3.up),0.6);
This way origin will always be out of bounds of your object.
Your answer