HTML and CSS Reference
In-Depth Information
Gravity with Bounce and Applied Simple Elasticity
In physics, the
elasticity
of a bouncing ball refers to how much energy is conserved when
a ball bounces off a surface. We already covered a bit about conservation of energy when
we discussed balls colliding, but when we are simulating objects falling, we need to take a
slightly different path with our code. In
Example 5-15
,
we applied 100% elasticity and the
ball bounced forever. (Actually, this was only implied because we did not consider elasticity
at all.) However, in real life, balls usually lose some of their energy every time they bounce
off a surface. The amount of energy conserved depends on the material the ball is made from,
aswellasthesurfaceitisbouncingon.Forexample,arubberSuperBallismuchmoreelastic
than a cannonball and will bounce higher on the first bounce off a surface. Both will bounce
higher off a concrete surface than a surface made of thick mud. Eventually, both will come to
rest on the surface as all the energy is transferred away from the ball.
We can simulate simple elasticity by applying a constant value to the ball when it bounces off
the ground. For this example, we will set the
speed
of the ball to
6
pixels per frame and the
angle
to
285
. We will keep our
gravity
at
.1
but set a new variable named
elasticity
to
.5
. To make this more straightforward, we will also assume that the surface the ball is boun-
cing on does not add or subtract from the elasticity of the ball.
In
canvasApp()
, we would set the new properties like this:
var
var
speed
=
6
;
var
var
gravity
=
.
1
;
var
var
elasticity
=
.
5
;
var
var
angle
=
285
;
Wethenaddthenew
elasticity
propertytothe
ball
objectbecause,unlike
gravity
,elasti-
city describes a property of an object, not the entire world it resides within. This means that
having multiple balls with different values for elasticity would be very easy to implement:
var
var
ball
=
{
x
:
p1
.
x
,
y
:
p1
.
y
,
velocityx
:
vx
,
velocityy
:
vy
,
radius
:
radius
,
elasticity
:
elasticity
};
In the
drawScreen()
function, we still add the
gravity
value to the
y
velocity (
velocityy
).
However,instead ofsimply reversing the
y
velocity whenthe
ball
hitsthebottom ofthecan-
vas, we also multiply the
y
velocity by the
elasticity
value stored in the
ball.elasticity
property. This applies the elasticity to the bounce, preserving the
y
velocity by the percentage
value of
elasticity
for the object:
ball
.
velocityy
+=
gravity
;
iif
((
ball
.
y
+
ball
.
radius
)
>
theCanvas
.
height
) {
ball
.
velocityy
= -
(
ball
.
velocityy
)
*
ball
.
elasticity
;