The Essential Guide to HTML5

(Greg DeLong) #1

CHAPTER 4


By the way, we can't expect our players to put in angles using radians. They, and we, are too accustomed
to degrees (90 degrees is a right angle, 180 degrees is your arc when you make a u-turn, etc.). The
program must do the work. The conversion from degrees to radians is to multiply by pi/180.


Note: Most programming languages use radians for angles in trig functions. Flash uses degrees in
certain situations and radians in others, so in some ways JavaScript is less confusing by only using
radians.


With this background, I add to the information in the everything array indications as to whether there is
to be a rotation and, if so, the required translation point. This is my idea. It has nothing to do with HTML5 or
JavaScript, and it could have been done differently. The underlyingtask is to create and maintain
information on objects in the simulated scene. The canvas feature ofHTML5 provides a way to draw
pictures and display images, but it does not retain information on objects!


The items in the everything array for the second and third applicationsare themselves arrays. The first
(0th index) value points to the object. The second (1st index) is true or false. A value of true means that a
rotation angle value and x and y values for translation follow. In practice, this means that the inner arrays
have either two values, with the la st one being false, or five values.


Note: At this point, you may be thinking: she set up a general system just to rotate the cannon. Why
not put in something just for the cannon? The answer is we could, but the general system does work
and something just for the cannon might have had just as much coding.


The first application uses horizontal and vertical displacement values picked up from the form. The player
must think of the two separate values. For the second application, the player inputs two values again, but
they are different. One is the speed out of the mouth of the cannon and the other is the angle of the
cannon. The program does the rest. The initial and unchanging horizontal displacement and the initial
vertical displacement are calculated from the player's input: the velocity out of the cannon and an angle.
The calculation is based on standard trigonometry. Luckily, JavaScript provides the trig functions as part
of the Math class of built-in methods.


Figure 4-9 shows the calculation of the displacement values from the out of cannon and angle values
specified by the player. The minus sign for the vertical is due to the way JavaScript screen coordinates
have y values increasing going down the screen.

Free download pdf