- Home /
Not detecting a simple collision?
Hey, folks! I might be crazy, but...for me, the first print statement will print "Normal was: (0,1,0)", but the second print statement then prints nothing. What am I doing wrong, here? I'm not really sure what the heck is up. Why would it print that statement, but then not respond to the conditional?
function OnCollisionEnter(collision: Collision)
{
for (var contact : ContactPoint in collision.contacts)
{
print("Normal was:" + contact.normal);
if(contact.normal == Vector3(0.0, 1.0, 0.0))
{
print("Detected collision!");
}
}
}
Answer by Owen-Reynolds · Nov 12, 2011 at 03:08 PM
It's a float issue. The normal is a computed value, so is probably something like (0, 0.999999, 0.00001)
. The inspector only shows 1 decimal. You can print contact.normal.x*100000 to see more. But, even regular prints often "round to the nearest" on the screen.
The official computery way is to check: if(Mathf.Approximately(contact.normal.x, 0) && Mathf.Approximately(contact.normal.y, 1) ...)
An example of float rounding: 1/3 is 0.3333 with 3's forever. The computer can only store about seven of them. So (1/3)*3 is 0.9999999. Additionally, the computer uses binary, so really stores the 1/2's place, the 1/4ths place, the 1/8ths place ... . One fifth is the non-repeating decimal 0.2 for us, but 1/5th in binary is 1/8 + 1/16 + 1/128 ... and repeats, so has to be rounded to the nearest.
I missed that! You're right: comparing floats equality almost never results true, unless both floats were generated in the same manner (both are constants, for instance). For Vector3 comparison, I would use a margin error:
if ((contact.normal-Vector3(0.0, 1.0, 0.0)).magnitude < 0.001){
...
You gentlemen are geniuses.
I'm trying to make it so that my character can jump through ceilings and land on them as floors--like in most platfor$$anonymous$$g games...I guess I'll start another topic! Thanks again.
Answer by aldonaletto · Nov 12, 2011 at 11:46 AM
Check if that damned Collapse button in the Console pane isn't pressed: if you click this SOB button by mistake, the Console doesn't show repeated lines, driving us crazy.
Nope! Not a collapse button issue, I don't think. It's not pressed. And second of all, the second print statement is different from the first--so it wouldn't be collapsed, right?
Does this code work for you? I feel like I'm taking crazy pills here.