- Home /
Collision contacts problem
I've written a little bit code to detect when my character hits the edge of a platform:
if(!hit.collider.gameObject.CompareTag("Platform")) return;
if(hit.contacts[0].normal == -Vector3.forward){
print("hit side");
} else {
print(hit.contacts[0].normal +" : "+ -Vector3.forward);
}
for debugging purposes I wanted to print the normal of the ContactPoint if it doesn't equal the back of the platform. but instead of the IF statement detecting that this is the case instead it prints (0.0, 0.0, -1.0) : (0.0, 0.0, -1.0)
now im my book this shows that the IF statement is getting it completely wrong... what possably could cause such a thing?
I was going to suggest that for some reason the float values weren't quite identical but the documentation says that the == operator for Vector3 returns true "for vectors that are really close to being equal". Weird indeed.
Answer by GuyTidhar · Apr 04, 2012 at 02:01 PM
You probably need to use "Mathf.Approximately". The floating point might be very similar but does not equals due to precision on CPU/GPU levels so you need an approximate.
e.g.
if ( Mathf.Approximately(hit.contacts[0].normal.x, -Vector3.forward.x)
&& Mathf.Approximately(hit.contacts[0].normal.y, -Vector3.forward.y)
&& Mathf.Approximately(hit.contacts[0].normal.z, -Vector3.forward.z) )
print("hit side");
} else
{
print(hit.contacts[0].normal +" : "+ -Vector3.forward);
}
As @clfischer pointed out, this is what is done by operator== regarding Vector3.
The problem here is that printing out the value of a Vector3 only gives 2 digits. $$anonymous$$athf.Approximately checks the 6th (or 7th) digit (after formatted to scientific: n.dddddd*10^y).
To see more digits, use the formatted string:
print(hit.contacts[0].normal.ToString("F5") +" : "+ -Vector3.forward.ToString("F5"));
To compare the two vectors, the best way is to check the dot product. If the dot product is close to 1, then the two unit vectors are almost identical:
float threshold = 0.99f;
if( Vector3.Dot(hit.contacts[0].normal, -Vector3.forward) >= threshold )
{
print("hit side");
}
@$$anonymous$$ryptos Before even reading these responses I started using Vector3.Dot it works fairly well and even allows me to include the other sides of the object. Thanks.