Cover by Raffaele Cecco

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

A Cannon Simulation Using Vectors

Now that we’ve defined the vector object, we can use it to develop a simple cannon simulation (Figure 7-5). First, I should qualify the term “simulation”: our goal is not to try to replicate with absolute realism the physics of a cannon, but rather to create a simulation that is realistic enough for applications like games. Even the most advanced physics in games have to suspend reality somewhat. For example, human characters in games do not simulate physics to remain upright and walk, and aircraft in games do not simulate all the physics of flight to remain airborne.

Note

Strictly speaking, for accurate simulations, you should factor the time elapsed per frame into your calculations. However, for the purposes of this demonstration, we’ll assume a frame rate of 30 milliseconds. In actuality, timers on certain browsers are not particularly accurate anyway, so the lack of time calculations is no great loss.

Simple cannon simulation using vectors and HTML5 Canvas

Figure 7-5. Simple cannon simulation using vectors and HTML5 Canvas

The simulation uses HTML5 Canvas to draw the graphics, although you could adapt it to work with any number of rendering methods in the browser (SVG, CSS3, etc.). The graphics are deliberately basic to keep the code’s focus on the use of vectors and the calculations required.

The cannon simulation will use vectors for the following:

  • To represent the aiming direction of the cannon

  • To represent ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required