Reputation: 133
I'm working on creating an air hockey-like game using HTML5 canvas and JavaScript. I've gotten pretty far, but detecting the collision of the mallet and the ball has me stumped. I've tried using the distance between the two circles and distance squared (to conserve CPU by bypassing square root). I can't figure out why the collision is not being detected.
Here's what I have: http://austin.99k.org/z_Archive/Air_Hockey/
Please take a look and help me figure it out. The source files are somewhat commented.
Upvotes: 2
Views: 4692
Reputation: 36773
Your hit function is wrong. You should simply compute the distance between the two points (which you do correctly), and compare that to the minimum distance between the mallet and ball.
For example,
return distance_squared < radii_squared
You're actually (effectively) doing:
return -COLLIDEDISTANCE < radii_squared - distance_squared && radii_squared - distance_squared < COLLIDEDISTANCE
Which requires any hit to be within 2 units of the edge, but the numbers I saw running through hit() implied you're at a scale factor that makes a single unit less than one pixel.
Upvotes: 3