HTML and CSS Reference
In-Depth Information
if (y2 > -ball.radius) {
//do bounce
}
The rest of the bounce should be obvious.
Then you rotate everything back, using the original formula. This gives you updated values for
x1
,
y1
,
ball.vx
, and
ball.vy
. All you need to do is reset the actual position of the
ball
instance by adding
x1
and
y1
to
line.x
and
line.y
.
Take some time to test this example. Try different rotations of the line, and different positions of both the
line and ball. Make sure it all works fine.
Optimizing the code
You've already seen some examples of changing code a bit to make it more optimized. This usually
involves doing things once instead of multiple times, or not doing them at all, unless you're sure they need
to be done.
The code in the previous example was written for clarity; there's a lot happening on every frame that
doesn't need to be. Much of that code needs to execute only when the ball has actually hit the line. Most of
the time, you just need the basic motion code, and the bare minimum of calculation to check whether the
ball has hit the line. In other words, you just need to be able to calculate the
if
statement:
if (y2 > -ball.radius) {
//do bounce
}
Here, you do need the
y2
variable. And in order to get that, you need
x1
and
y1
, and
sin
and
cos
. But if
the ball hasn't hit the line, you don't need
x2
, or
vx1
and
vy1
—those can go
inside
the
if
statement.
Also, if there's no hit, there's no need to rotate anything back or reset the ball position. So, all the stuff
after
the
if
statement can go inside the
if
statement as well. You wind up with this optimized version of the
drawFrame
function (which you'll find in
05-angle-bounce-opt.html
):
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
//normal motion code
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
//get position of ball, relative to line
var x1 = ball.x - line.x,
y1 = ball.y - line.y,
//rotate coordinates
y2 = y1 * cos - x1 * sin;
//perform bounce with rotated values