HTML and CSS Reference
var p = this.p;
p.t += dt;
p.x = p.x0 + p.vx0 * p.t + 0.5 * p.ax * (p.t * p.t);
p.y = p.y0 + p.vy0 * p.t + 0.5 * p.ay * (p.t * p.t);
Much of the code consists of setting up the initial values for the ball's position and velocity, and the actual
position is calculated using just the two lines at the bottom of the update function. These two lines mirror Equa-
tion 4 exactly, once for the x direction and once for the y direction. Finally, the gameLoop function is written
explicitly; it clears the Canvas before updating the ball's position and calling the draw method. If you want to
follow the path of the ball explicitly, you can remove the call to this.clear() and the ball leaves a trail.
Switching to an Iterative Solution
Equation 4 is a closed form solution in that you can express the exact position of the cannonball at any point in
time just by plugging t into the one equation. You can do this because you are modeling such a simple object.
The minute you get something more complex, such as an object involving interactions with other objects or
input from the user, you won't come up with a closed form solution without hiring some mathematicians from
Instead, you need to go back to your first set of differential equations (Equations 1 through 3) and turn them
into something more computer-friendly. The easiest way to do this is to use a discrete integration technique .
Discrete integration means instead of using calculus to determine an exact solution, you can use an actual, albeit
small value for dt to find an approximate solution. The most commonly used method for discrete integration
also happens to be the simplest and is known as Forward Euler , named after the famous Swiss mathematician
Leonhard Euler. This method translates well to computer simulation. This means you can assume that over any
small chunk of time, any of your potentially changing values, such as acceleration or velocity, are constant. The
velocity and position equations now become the following:
Equation 5: v = v t-1 + a t × dt
Equation 6: p = p t-1 + v t × dt
In the preceding equations, dt is no longer an instantaneous delta but rather is a small but measurable amount
of time. In the game, it will be approximately 1/30th of a second, or one frame of animation.
These equations aren't written in terms of v 0 and p 0 (velocity and position at time zero) but rather in terms
of v t-1 and p t-1 (velocity and position at the last simulation step). This means that you can't say exactly where
the ball is at any given point just by plugging in a value of t ; rather you can incrementally calculate only the
position based on the previous position.