Comparison of two angles.

Started by
3 comments, last by Zakwayda 17 years, 6 months ago
Hi, here's the problem: i have the ball that moving across the 2D screen, and number of other objects. Some of them has a "shield", this shield is moving around the object, so when the ball is closing i need to check if my shield protecting the object or not. Actually i have two angles: first angle of approaching ball against the object, second - shield position across the object. The value rangle of my angles are: 0.0f - 360.0f My problem is that i can't find a right way to compare this two angles. I need to check this: if (Angle1-Angle2 < 90.0f) (shield covers 1/4 space of the object, 90 degree) Hit the shield else Hit the object But if Angle1's value is 7.0f and Angles2's value is 355.0f the ball hits the shield, but my logic here when (A1-A2 < 90) will fail. Please help. Thanks!
Advertisement
Quick answer: take the dot product of the normalized vector from the object to the center of the shield, and the normalized vector from the object to the ball. If the dot product is >= cos(rad(45)), the shield is in place to deflect the ball. Otherwise, the object is exposed.
Add something like
delta = Angle1-Angle2;if (delta < 0) delta+=360.0f;if (delta < 90.0f) etc etc.
delta = Angle1-Angle2;if (delta < -180) delta plus= 360.0f;if (delta > 180) delta -= 360.0f;if (abs(delta) < 45.0f){   //You collision code}

This is just MHO, but I think it's best to avoid working directly with angles (as in the above examples) if you can avoid it. All of the 'if this is less than that, add 360' stuff really isn't very expressive of the problems we're trying to solve, or their solutions. It's also error prone and annoying to code.

Just about any problem that can be solved using these methods can be solved more straightforwardly using signed angles and a little vector math. I'm not positive I got the solution exactly right in my previous post, but something along those lines should work.

This topic is closed to new replies.

Advertisement