Simple Gravity
A very simple yet seemingly realistic gravitational effect can be
achieved by applying a constant gravity value to the y
velocity of an object moving on a vector. To
do this, select a value for gravity, such as .1
, and then add that value to the y
velocity of your object on every call 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 we did not apply any gravity, the
ball would simply keep moving on that vector until it left the 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
speed
=
4
;
var
angle
=
305
;
var
radians
=
angle
*
Math
.
PI
/
180
;
var
radius
=
15
;
var
vx
=
Math
.
cos
(
radians
)
*
speed
;
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
p1
=
{
x
:
20
,
y
:
theCanvas
.
height
-
radius
};
var
ball
=
{
x
:
p1
.
x
,
y
:
p1
.
y
,
velocityx
:
vx
,
velocityy
:
vy
,
radius
:
radius
};
If we want to add gravity to the application, we would first
create a new variable named gravity
and set it to a constant value of .1
:
var
gravity
=
.
1
;
Next, in the drawScreen() ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.