HTML and CSS Reference
In-Depth Information
The first thing that the collision-handling code needs to do is figure out the angle between the two balls,
which you'll recall from the trigonometry in Chapter 3, you can do with
Math.atan2(dy, dx)
. You'll store
the cosine and sine calculations, as you'll be using them over and over:
//calculate angle, sine, and cosine
var angle = Math.atan2(dy, dx),
sin = Math.sin(angle),
cos = Math.cos(angle);
Then, you need to perform the coordinate rotation for the velocity and position of both balls. Let's call the
rotated positions
x0
,
y0
,
x1
, and
y1
and the rotated velocities
vx0
,
vy0
,
vx1
, and
vy1
.
Because you are use
ball0
as the “pivot point,” its coordinates are 0, 0. That won't change even after
rotation, so you can just write this:
//rotate ball0's position
var x0 = 0,
y0 = 0;
Next,
ball1
's position is in relation to
ball0
's position. This corresponds to the distance values you've
already figured out,
dx
and
dy
. So, you can rotate those to get
ball1
's rotated position:
//rotate ball1's position
var x1 = dx * cos + dy * sin,
y1 = dy * cos - dx * sin;
Now, rotate all the velocities. You should see a pattern forming:
//rotate ball0's velocity
var vx0 = ball0.vx * cos + ball0.vy * sin,
vy0 = ball0.vy * cos - ball0.vx * sin;
//rotate ball1's velocity
var vx1 = ball1.vx * cos + ball1.vy * sin,
vy1 = ball1.vy * cos - ball1.vx * sin;
And here's all the rotation code in place:
function checkCollision (ball0, ball1) {
var dx = ball1.x - ball0.x,
dy = ball1.y - ball0.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < ball0.radius + ball1.radius) {
//calculate angle, sine, and cosine
var angle = Math.atan2(dy, dx),
sin = Math.sin(angle),
cos = Math.cos(angle),
//rotate ball0's position
x0 = 0,
y0 = 0,