- Home /
Else Statement Not Working
I'm checking to see if an object is in front of another before continuing, and this works. But when I try to do an alternate action for when the opposite happens (they're behind), it will always do the latter. Any help out there? I can not figure out why this doesn't work and it's driving me insane.
What should happen is that if we're not blocking, get hit by the ball. If we are blocking and facing the ball, do the action, if we are blocking and not facing the ball, get hit. But instead, if we're blocking, it always hits and never catches - regardless of if they're in front of us or not.
function OnTriggerEnter(hit : Collider){
if(hit.gameObject.tag == "Ball"){
var toTarget = (hit.transform.position - transform.position).normalized;
if(!isBlocking){
GetHit();
}else if(Vector3.Dot(toTarget, transform.forward) < 0){
CatchBall();
}else{
GetHit();
}
}
}
This is not enough info, because we don't know how far away hit could be, and you don't normalize heading. You also don't explain what Random.value is for. Also, use CompareTag ins$$anonymous$$d: http://answers.unity3d.com/questions/40975/why-does-comparetag-exist.html
Okay, I changed it up a bit and I'm still having the same problems. Change is in the initial question.
Okay. Now it works, but it's backwards. I catch the ball when I turn around, but get hit when I'm facing it. It should be the other way around, but turning it back to < will always make me get hit.
Transform.forward is the local Z vector; it may not be "forward" at all. We don't know how your mesh is oriented, or where the local origins are. With the greater than symbol, I'd say your code looks usable, but there's no way to write this code for every case. It's dependent on alignment.
Answer by Xatoku · Jan 31, 2012 at 07:07 PM
I figured it out. What happened was that the ball was being caught properly the entire time, it just hit the player afterward because the else statement did not check if the ball had been caught or not. Everything is fixed now, thanks for the help.