HTML and CSS Reference
InDepth Information
Simple Gravity
A very simple yet seemingly realistic gravitational effect can be achieved by applying a con
stant gravity value to the
y
velocity of an object moving on a vector. To do this, select a value
forgravity,suchas
.1
,andthenaddthatvaluetothe
y
velocity ofyourobject oneverycall to
drawScreen()
.
For this example, let's simulate a ball with a
radius
of
15
pixels being shot from a cannon
that rests near the bottom of the canvas. The ball will move at a
speed
of
4
pixels per frame,
with an
angle
of
305
degrees. This means it will move up and to the right on the canvas. If
wedidnotapplyanygravity,theballwouldsimplykeepmovingonthatvectoruntilitleftthe
canvas. (Actually, it would keep moving; we just would not see it any longer.)
You have seen the code to create an effect like this already. In the
canvasApp()
function, we
would create the starting variables like this:
var
var
speed
=
4
;
var
var
angle
=
305
;
var
var
radians
=
angle
*
Math
.
PI
/
180
;
var
var
radius
=
15
;
var
var
vx
=
Math
.
cos
(
radians
)
*
speed
;
var
var
vy
=
Math
.
sin
(
radians
)
*
speed
;
Next we create the starting point for the ball as
p1
, and then we create a dynamic object that
holds all the values we created for the
ball
object:
var
var
p1
=
{
x
:
20
,
y
:
theCanvas
.
height

radius
};
var
var
ball
=
{
x
:
p1
.
x
,
y
:
p1
.
y
,
velocityx
:
vx
,
velocityy
:
vy
,
radius
:
radius
};
Ifwewanttoaddgravitytotheapplication,wewouldfirstcreateanewvariablenamed
grav
ity
and set it to a constant value of
.1
:
var
var
gravity
=
.
1
;
Next, in the
drawScreen()
function, we apply this gravity value to the
ball
object when it is
drawn to the canvas (
ball.velocityy += gravity
). We want the ball to stop moving when
it hits the “ground” (the bottom of the canvas), so we test to see whether the
y
position of the
ball
plusthe
radius
oftheball(theouteredge)haspassedthebottomofthecanvas(
ball.y
+ ball.radius <= theCanvas.height
). If so, we stop the ball's movement:
iif
(
ball
.
y
+
ball
.
radius
<=
theCanvas
.
height
) {
ball
.
velocityy
+=
gravity
;
}
else
else
{
ball
.
velocityx
=
0
;