The Essential Guide to HTML5

(Greg DeLong) #1

CHAPTER 4


Figure 4-4. Opening screen of the slingshot application


For the slingshot, I decided I wanted the ball to keep going until it hit the ground. However, if the chicken
was hit, I wanted it to be replaced by feathers, as shown in Figure 4-5. Notice that the strings of the
slingshot remain where they were when the mouse button was released and the ball took flight. I found I
needed more time looking at the strings in order to plan my next shot. If you want, you can change the
game so that the strings snap back to their original position or create a new-game button. In my example,
the game is replayed by reloading the HTML file.


Figure 4-5. The ball lands on ground after hitting the chicken. Only feathers remain.


The programming for these applications uses many of the same techniques demonstrated in the bouncing
ball applications. The repositioning of the ball in flight is only as different as it needs to be to simulate the
effects of the vertical displacement changing because of gravity. The slingshot application provides a
new way for the player to interact with the application, using drag and drop actions with the mouse.


The cannonball with cannon and the slingshot use drawing features for the cannon and slingshot and
external image files for the original targets and hit targets. If you want to change the targets, youll need to
find image files and upload them with the application. The complete applications are available at
http://www.friendsofed.com/downloads.html.


Critical requirements...................................................................................................................................


Our first requirement is to produce animation by setting up an event to occur at fixed intervals of time, and
then setting up a function to handle the event by repositioning the ball and checking for collisions. We
covered this in the previous chapter on the bouncing ball application. Whats new here is the calculation
for simulating gravity. The calculation indicated by a simple physics model works out a new vertical
displacement based on changing the vertical displacement by a constant amount and then computing the
average of the old and new displacements to compute the new position.



  • The horizontal displacement (held by variable dx) is the horizontal velocity (horvelocity) and
    does not change. In code: dx = horvelocity;

Free download pdf