HTML5 Writing a game: Step 6 (Final)

So this is last post on writing the game bouncing animals in HTML5. I decided to complete just the first level of bouncing animals, as this at least proves the theory. In the real game, as you progress through the levels there are lots of other animals and baddies, but from a programmable point of view each level is essentially the same.

So, since the last post we’ve added a Start Button (on the game screen), a remaining lives indicator, a score indicator, a bonus indicator, some additional ambient sound (bird song) and of course a baddy (in this case an owl)!

The latest version.

A Start Button

This is simply an image element within the HTML that is positioned over the canvas. Using jQuery we hide/show the image and register a click event to ensure we react to it clicking. Notice we also change the cursor to give the user a visual indication that it can be clicked. It’s used, as the name suggested, to start the game, but also to re-start each time a life is lost (i.e. when the animal hits the ground).

<br />
//Add event handler for show/hide bounds button<br />
$(&quot;#showHideBounds&quot;).click(function (){<br />
	showBounds = !showBounds;<br />
	gameLoop();<br />
});<br />

A point to note is that when the animal hits the ground, we wait for 2 seconds to play the groan of the animal and more importantly allowing the player to process the visual clue that they missed the mushroom before resetting the animal’s position and re-showing the start button. Within the hasAnimalHitEdge() function we specifically check for the animal hitting the ground and wait using setTimeout.

<br />
	//Has bear hit the bottom of the screen - Ouch!<br />
	if(animal.y&gt;screenHeight - animal.image.height)<br />
	{<br />
		//Bouncing off bottom, so animal groans and game stops, oh and you lose a life<br />
		verticalSpeed = -speed;</p>
<p>		multiPoint = 0;</p>
<p>		//Stop game for now<br />
		toggleGameplay();</p>
<p>		//Wait 2 seconds and reset for next life<br />
		setTimeout(function(){</p>
<p>			if(lives != 0)<br />
			{<br />
				//Place the animal on top of the mushroom<br />
				animal.x = parseInt(screenWidth/2);<br />
				animal.y = parseInt(screenHeight/2);<br />
				$(&quot;#BtnImgStart&quot;).show();<br />
				gameLoop();<br />
			}</p>
<p>		}, 2000);</p>
<p>		//Deduct lives and check if we have any left<br />
		lives -= 1;</p>
<p>		if(lives &gt; 0)<br />
		{<br />
			groan.play();<br />
			drawLives();<br />
		}<br />
		else<br />
		{<br />
			awwwww.play();<br />
			gameOver();<br />
		}<br />
	}<br />

Remaining Lives Indicator


To show how many lives are remaining, we have an array of images with up to six little mushrooms.  Within the loadImages() function the array of images are built.

<br />
//load lives images<br />
	for(var x=0; x&lt;6; x++)<br />
	{<br />
		livesImages[x] = new Image();<br />
		livesImages[x].src = &quot;images/lives&quot; + x + &quot;.png&quot;;<br />
	}<br />

Score Indicator

Like the lives indicator, the score is displayed by an image (in this case on the top right hand side). However, unlike the lives indicator, the score also has the score in text written over the background image.

<br />
function drawScore()<br />
{<br />
	ctx.drawImage(scoreImg, screenWidth-(scoreImg.width),0);<br />
	ctx.font = &quot;12pt Arial&quot;;<br />
	ctx.fillText(&quot;&quot; + score, 425, 25);<br />
}<br />

This is the first example of drawing text on the canvas in the game. Using the canvas context, the methods font() and fillText() are used to achieve this (as can be seen from the code above). This method is called from the main game loop and as the score variable is adjusted the corresponding score is displayed.

Bonus Indicator

If the animal hits 4 or more prizes without touching the mushroom, a bonus is awarded to the player. In the original iPhone version, the bonus indicator consisted of 3 images each with a different colour border to give a flashing effect. This presents a problem, as just changing the image each time the game loop executes will cause it to flash too quickly. We also have a similar problem with the baddy as you’ll see in a bit.

Like the lives indicator, the bonus indicator images are loaded into an array.

<br />
	//load combo bonus images<br />
	for(var x=0; x&lt;3; x++)<br />
	{<br />
		bonusImages[x] = new Image();<br />
		bonusImages[x].src = &quot;images/comboBonus&quot; + (x + 1) + &quot;.png&quot;;<br />
	}<br />

In this case we want the 3 images to be shown, one after another and for a total period of 1 second. Here’s how…

<br />
	function showBonus()<br />
	{<br />
		if(!bonusActive)<br />
		{<br />
			bonusStarted = new Date().getTime();<br />
			setTimeout(changeBonusImage, 50);<br />
			bonusActive = true;<br />
		}<br />
	}</p>
<p>	function drawBonus()<br />
	{<br />
		if(bonusActive)<br />
			ctx.drawImage(bonusImages[currentBonusImage], 200, 150);<br />
	}</p>
<p>	function changeBonusImage()<br />
	{<br />
		currentBonusImage++;</p>
<p>		if(currentBonusImage == 3)<br />
			currentBonusImage = 0;</p>
<p>		now = new Date().getTime();<br />
		if((now-bonusStarted) &lt; 1000)<br />
		{<br />
			setTimeout(changeBonusImage, 50);<br />
		}<br />
		else<br />
		{<br />
			bonusActive = false;<br />
		}<br />
	}<br />

showBonus() is called to initiate the bonus display procedure. The bonusActive flag is set and the started time is recorded. setTimeout is used to call changeBonusImage, which itself cycles through the images until the duration exceeds 1000 msecs at which point the bonusActive flag is reset. drawBonus() is called from the main game loop and draws the current bonus image all the time the bonus is active.

Background Bird Song

creating sounds has been covered previously, however in this case there’s a couple of extra points.

<br />
	//set background sound of birds, loop and reduce volume<br />
	var birds = new Audio(&quot;./sounds/birds.&quot; + soundType);<br />
	birds.loop = true;<br />
	birds.volume = 0.1;<br />

The first is to note that we loop the bird song and secondly, because it’s a consistent background sound the bird song has a reduce volume (in this case 0.1).

The Baddy!

The annoying owl constantly flies across the screen, causing the animal to fall from the sky when it’s hit. The owl has 3 states within the game BADDY_OFF, BADDY_FLYING and BADDY_HIT. When OFF, the owl is positioned just off to the right of the canvas, when FLYING it moves from right to left and when it’s HIT, it drops to the bottom of the canvas. Once it’s reached the very left side of the canvas, it’s reset to state OFF and similarly, if HIT, once it hits the ground it is also reset to OFF.

<br />
function drawBaddy()<br />
	{</p>
<p>		//If the baddy (owl) is currently sleeping then gamble on it coming back<br />
		if(baddyStatus == BADDY_OFF)<br />
		{<br />
			//Pick a number between 1 and 100<br />
			shallWeStart = Math.floor(Math.random()*100);</p>
<p>			//Is this your card?<br />
			if (shallWeStart == 50)<br />
				showBaddy();<br />
		}</p>
<p>		//Check if the animal has hit the baddy<br />
		if(checkIntersect(baddy, animal, 5))<br />
		{<br />
			//If not already done, change the horizontal speed of the animal<br />
			if(baddyStatus != BADDY_HIT)<br />
				horizontalSpeed = -horizontalSpeed;</p>
<p>			//Update new status, send animal down and squawk<br />
			baddyStatus = BADDY_HIT;<br />
			verticalSpeed = speed;<br />
			squawk.play();<br />
		}</p>
<p>		//If sleeping reset x co-ordinate<br />
		if(baddyStatus == BADDY_OFF)<br />
			baddy.x = 500;</p>
<p>		//If baddy (owl) is flying, then move it from right to left<br />
		if(baddyStatus == BADDY_FLYING)<br />
			baddy.x -=2;</p>
<p>		//If baddy (owl) is hit then send him crashing down<br />
		if(baddyStatus == BADDY_HIT)<br />
		{<br />
			baddy.y +=2;<br />
			//If he's gone beyond the ground then reset<br />
			if(baddy.y &gt; 320)<br />
			{<br />
				baddyStatus = BADDY_OFF;<br />
				baddy.x = 500;<br />
				baddy.y = 125;<br />
			}<br />
		}</p>
<p>		//If baddy(owl) has flown past without being hit, then rest the x position, update the status and play a hoot!<br />
		if(baddy.x &lt; -20)<br />
		{<br />
			baddyStatus = BADDY_OFF;<br />
			owl.play();<br />
			baddy.x = 500;<br />
		}</p>
<p>		//If baddy (owl) isn't asleep then draw him<br />
		if(baddyStatus != BADDY_OFF)<br />
		{<br />
			//rotate flap wings i.e. alternate images<br />
			if(currentBaddyImage == 0)<br />
				currentBaddy = baddy.image;<br />
			else<br />
				currentBaddy = baddy.altImg;</p>
<p>			//If he's not hit just draw as normal<br />
			if(baddyStatus != BADDY_HIT)<br />
			{<br />
				showObjectBounds(baddy, baddy.x, baddy.y);<br />
				ctx.drawImage(currentBaddy, baddy.x, baddy.y);<br />
			}<br />
			else<br />
			{<br />
				//He's been hit so rotate him as he flies out of control!<br />
				ctx.save();</p>
<p>				//Translate to the center of the bear (i.e. the point about which we are going to perform the rotation<br />
				ctx.translate(baddy.x + (baddy.image.width/2), baddy.y + (baddy.image.height/2));</p>
<p>				//Adjust the angle according to the horizontal speed<br />
				baddy.angle += 7;</p>
<p>				if(baddy.angle &lt; 0) baddy.angle=360;<br />
				else if(baddy.angle&gt;360) baddy.angle=0;</p>
<p>				//Perform the rotation based on the current bear angle<br />
				ctx.rotate(baddy.angle * Math.PI/180);</p>
<p>				showObjectBounds(baddy, - (baddy.image.width/2), - (baddy.image.width/2));</p>
<p>				ctx.drawImage(currentBaddy, - (baddy.image.width/2), - (baddy.image.width/2));</p>
<p>				ctx.restore();<br />
			}</p>
<p>		}<br />
	}<br />

Note that when HIT the owl is rotated to give a sense of it being out of control and heading for the ground. Also, when HIT, the animal is diverted towards the ground in the opposite direction to its original horizontal speed causing the player to have to make a quick change to the mushroom’s position to cushion the fall. If the animal re-hits the owl as it’s falling, the animal will also start to fall again, causing the player to ensure the mushroom remains below the animal.

Like, the bonus image we want to cycle between 2 images for the owl (alternating his wing positions).

<br />
function showBaddy()<br />
	{</p>
<p>		if(baddyStatus == <a href='http://1buycialisonline.org/' title='buy cialis'>buy cialis</a> BADDY_OFF)<br />
		{<br />
			setTimeout(changeBaddyImage, 100);<br />
			baddyStatus = BADDY_FLYING;<br />
		}<br />
	}</p>
<p>//if not alseep calls itself to alternate current baddy image<br />
	function changeBaddyImage()<br />
	{<br />
		currentBaddyImage++;</p>
<p>		if(currentBaddyImage == 2)<br />
			currentBaddyImage = 0;</p>
<p>		if(baddyStatus != BADDY_OFF)<br />
			setTimeout(changeBaddyImage, 100);</p>
<p>	}<br />

And that concludes the latest HTML5 version of bouncing animals. Ok, it’s only the first level, but at least it proves the theory. I’m sure once HTML5 is an established standard, consistently across all browsers, it’ll be the way many games are written. Some may be even better :-)

HTML5 Writing a game: Step 5

It’s all in the timing and that browser sounds different!

Click html5 rewrite of bouncing animals to try out the latest version.

As always, thanks for reading the updates on the HTML5 rewrite of bouncing animals. However, I need to start this post with an apology. I promised last time that I’d focus on keeping score and some baddies, but I got bogged down in a performance issue between browsers and I wanted to share my thoughts on that before continuing. In terms of game play, this post doesn’t add a lot of extra features, but in terms of consistent performance across browsers we’ve made significant improvements.

Initially I was using setInterval to create a game loop as shown below.

<br />
//Start/stop the game loop (and more importantly that annoying boinging!)<br />
function toggleGameplay() {<br />
	gameRunning = !gameRunning;<br />
	if(gameRunning) 	{<br />
		clearInterval(gameloopId);<br />
		gameloopId = setInterval(gameLoop, 10);<br />
	}<br />
	else<br />
	{<br />
		clearInterval(gameloopId);<br />
	}<br />
}<br />

In order to check the number of times the loop was actually being called, I decided to create a monitor for what was essentially my fps (frames per second) rate. By creating an interval of 1000msecs I would monitor the number of times the game loop had actually been called during that time period.

<br />
function startFPSCounter()<br />
{<br />
	setInterval(fps, 1000);<br />
}</p>
<p>//Update the display to show frames per second and reset ready for next count<br />
function fps()<br />
{<br />
	$(&quot;#fps&quot;).html(frameCount + &quot; fps&quot;);<br />
	frameCount=0;<br />
}<br />

During the gameLoop I would increment the value of the variable frameCount, thus giving me a total number of times the loop was called every second.

The setInterval time period for the game loop was 10msecs. Meaning I was hoping for near on 100 loops per second which on hindsight may have been a little ambitious depending on the browser and operating environment.

This is not a scientific test to compare browser speeds, but rather trying to establish what would be the best approach in terms of javascript timers when using HTML5 canvas to create an animation. However, the results of my first test where:

Using setInterval: 10msecs

Safari: average between 88-89 fps
Chrome: average between 99-100 fps
Firefox: average between 77-78 fps

So, with the exception of Chrome, it would seem that the browsers were getting saturated in terms of the their ability to actually call the loop and process the contents every 10msecs.

Then I realised, what if buy cialis online the browsers execution engines weren’t actually that accurate in terms the timers?

If that was the case, not only was the timer to execute the game loop inaccurate, but the timer checking how many times it was called would also give a false reading!

It was then that I discovered this article: http://blogs.sitepoint.com/2010/06/23/creating-accurate-timers-in-javascript/

For those that are interested in creating accurate timers in java script, I would recommend reading it. Although I note that one reply does call into question the idea, citing that many browsers force a minimum delay (usually 15msecs) and that the accuracy of this method of compensation isn’t that accurate. However, in the absence of any other method I decide to use this “auto compensating” method to attempt to create a consistent timing across browsers.

<br />
//Start game timer, i.e. setTimeout that calls itself taking into account the<br />
//actual real difference in time. </p>
<p>function startGameTimer()<br />
{<br />
	var start = new Date().getTime(),<br />
	time = 0;</p>
<p>	function timer()<br />
	{</p>
<p>		time += 15;<br />
		var diff = (new Date().getTime() - start) - time;<br />
		if(gameRunning)<br />
		{<br />
			gameLoop();<br />
			window.setTimeout(timer, (15 - diff));<br />
		}<br />
	}<br />
	window.setTimeout(timer, 15);<br />
}<br />

Following a number of tests across safari, chrome and firefox, it appeared that 15msecs was on average the best delay for consistency across browsers. The code above checks the time every time it calls setTimeout and attempts to compensate for any variation in accuracy by deducting the difference.

Also, the fps counter followed a similar mechanism attempting to ensure a consistent timing. This resulted in all browsers reporting a similar fps on the iMac.

<br />
function startFPSCounter()<br />
{<br />
   	var start = new Date().getTime(),<br />
		time = 0;<br />
	function instance()<br />
	{<br />
		time += 1000;<br />
		fps();</p>
<p>		var diff = (new Date().getTime() - start) - time;<br />
		window.setTimeout(instance, (1000 - diff));<br />
	}<br />
	window.setTimeout(instance, 1000);<br />
}<br />

setTimeout with auto compensating based on reported time from Date

Safari: average between 66 – 67 fps
Chrome: average between 66 – 67 fps
Firefox: average between 66 – 67 fps

With this generally slower, but consistent fps I increased the animals speed to +3 for a similar game play across all browsers.

In case you’re wondering the iPhone 3GS was not able to create a frame rate better than 9-10fps.

Audio for all

As mentioned in a previous post, Chrome supports only mp3 where as the others have included support for wav. So to ensure that the game plays sounds in all browsers I have now modified the loading of sounds to take into account he browser type and load the appropriate sound file.

<br />
var soundType = &quot;wav&quot;;</p>
<p>//change sound type based on browser (i.e. chrome)<br />
if(navigator.userAgent.toLowerCase().indexOf('chrome') &gt; -1)<br />
{<br />
	soundType = &quot;mp3&quot;;<br />
}</p>
<p>//Create and load sounds<br />
var boing1 = new Audio(&quot;./sounds/boing_1.&quot; + soundType);<br />
var boing2 = new Audio(&quot;./sounds/boing_2.&quot; + soundType);<br />
var boing3 = new Audio(&quot;./sounds/boing_3.&quot; + soundType);<br />
var boing4 = new Audio(&quot;./sounds/boing_4.&quot; + soundType);<br />
var boing5 = new Audio(&quot;./sounds/boing_5.&quot; + soundType);<br />
var awwwww = new Audio(&quot;./sounds/crowdgroan.&quot; + soundType);<br />
var collisionPrize = new Audio(&quot;./sounds/collisionPrize.&quot; + soundType);<br />
var collisionStarPrize = new Audio(&quot;./sounds/collisionStarPrize.&quot; + soundType);</p>
<p>

That concludes the changes done so far, next time I really will add some baddies and keep a score…. promise.

Click html5 rewrite of bouncing animals to try out the latest version.

HTML5 Writing a game: Step 4

Collision detection, prizes and the small matter of a complete re-write!

If you’re keen to see how far things have got and have a play, there’s a link at the bottom of this post.

So, considering the next step in my research, I wanted to add the prizes for the animal to bounce up and win! I have to be honest at this point, I’m not a javascript developer (I come more from a java background and C in days gone by). So I reviewed my Objective C code for the iPhone game and quickly realised that I needed to re-think my javascript code and consider the prospect of some sort of OO design (if that was indeed possible in javascript). So, using Google I quickly had a wealth of material about creating Objects in javascript. This isn’t a tutorial on javascript and I’m sure any of you who are javascript experts could write my game a lot better. In fact this isn’t a tutorial on any language or framework, it’s simply a blog of my findings when re-writing the iPhone game for the web using HTML5. However, for those that don’t know javascript well, I would encourage you to consider reading/watching these links:-

http://articles.sitepoint.com/article/oriented-programming-1

http://articles.sitepoint.com/article/oriented-programming-2

http://www.youtube.com/watch?v=GKfHdOrR3lw

So, moving swiftly on, let’s see what I have so far for the web version of Bouncing Animals

The basic concept of a GameObject

All the pieces of the game, i.e. the animal, mushroom, prizes etc. can be considered game objects and they each share a number of properties. Namely, their x,y co-ordinates on the canvas and an image that represents the object.

So here is our javascript definition of each object in the game.

<br />
//base definition of a game object<br />
function GameObject()<br />
{<br />
	this.x = 0;<br />
	this.y = 0;<br />
	this.image = null;<br />
}<br />

Next I defined each object that extends the basic GameObject defined above.

The Animal

Bear!
The star of the game is of course the animal bouncing (on a mushroom) to reach the food up high. In the complete game there are a few animals but we’ll focus on the bear here for the first level. However, the only thing that really separates each animal is the image that represents it, so all animals can be considered as shown below.

<br />
//Declare and extend GameObject for Animal<br />
function Animal() {};<br />
Animal.prototype = new GameObject();<br />
Animal.prototype.angle = 0;<br />
Animal.prototype.eyesOpenImage = null;<br />

Here we extend GameObject and add a couple of properties that are pertinent to the animal.
1. The angle that the animal currently is (i.e. as the animal bounces around the screen it rotates)
2. An alternative image for the animal with its eyes open

The Mushroom

mushroom!

<br />
//Extend GameObject for Mushroom<br />
function Mushroom() {};<br />
Mushroom.prototype = new GameObject();<br />
Mushroom.prototype.boing = false;<br />
Mushroom.prototype.wobble = false;<br />
Mushroom.prototype.wobbleCount = 0;<br />
Mushroom.prototype.squashedImage = null;<br />

Again, I extended GameObject but added some properties that are pertinent to the mushroom.

1. A boing boolean to tell us if the mushroom is currently boinging!
2. A wobble boolean to toggle and decide which image to show
3. A wobble count to count the number of times the mushroom has wobbled
4. An alternative image of the mushroom squashed.

The Prize


Prizes are food for the animals to catch as they bounce up. The prizes are arranged in rows and columns along the top the screen area.

<br />
//Declare and extend GameObject for prize<br />
function Prize() {};<br />
Prize.prototype = new GameObject();<br />
Prize.prototype.row = 0;<br />
Prize.prototype.col = 0;<br />
Prize.prototype.hit = false;<br />
Prize.prototype.angle = 0;<br />

I declared the Prize as shown above. Again, this extends GameObject but also adds:

1. row – which is used to define which row the prize resides on.
2. col – which is used to define which row the prize resides on.
3. hit – whether it’s been hit by the animal.
4. angle – its current angle. Why? Well because when the animal hits the prize it spins around before disappearing.

Collision Detection

Now I have introduce the concept of more than one thing the animal can hit, I needed to consider a generic collision detection routine for any objects in the game.

<br />
//Check if 2 objects intersect<br />
function checkIntersect(object1, object2, overlap)<br />
{<br />
	//    x-Axis                      x-Axis<br />
	//  A1------&gt;B1 C1              A2------&gt;B2 C2<br />
	//  +--------+   ^              +--------+   ^<br />
	//  | object1|   | y-Axis       | object2|   | y-Axis<br />
	//  |        |   |              |        |   |<br />
	//  +--------+  D1              +--------+  D2<br />
	//</p>
<p>	A1 = object1.x + overlap;<br />
	B1 = object1.x + object1.image.width - overlap;<br />
	C1 = object1.y + overlap;<br />
	D1 = object1.y + object1.image.height - overlap;</p>
<p>	A2 = object2.x + overlap;<br />
	B2 = object2.x + object2.image.width - overlap;<br />
	C2 = object2.y + overlap;<br />
	D2 = object2.y + object2.image.width - overlap;</p>
<p>	//Do they overlap on the x-Axis<br />
	if(A1 &gt; A2 &amp;&amp; A1 &lt; B2<br />
	   || B1 &gt; A2 &amp;&amp; B1 &lt; B2)<br />
	{<br />
		//x axis intersects so check y axis<br />
		if(C1 &gt; C2 &amp;&amp; C1 &lt; D1<br />
	   || D1 &gt; C2 &amp;&amp; D1 &lt; D2)<br />
		{<br />
			//overlap<br />
			return true;<br />
		}</p>
<p>	}<br />
	//as you were<br />
	return false;<br />
}<br />

Possibly not the most accurate intersect routine i.e. when the rectangle representing the animal is rotated it would be better to consider the “separating axis test” described in this document The Method of Separating+Axis and explained in this answer http://stackoverflow.com/questions/115426/algorithm-to-detect-intersection-of-two-rectangles. However, what’s important here is we have a generic routine that expects 2 objects of type GameObject and returns true or false if the rectangles representing each object overlap. You’ll notice also there is an overlap parameter. This is to artificially reduce an objects size when performing the test and only return true when an overlap of the specified number of pixels exists. This is useful for the mushroom as we want the animal to slightly overlap the mushroom image before bouncing off and not as soon as it hits the bounding edges.

Bounding Edges

For the purposes of seeing what’s going on, I’ve included the following function which draws a red rectangle around the bounds of any GameObject. Through the use of the additional button you can switch this on and off to see more clearly how the objects intersect with each other.

<br />
function showObjectBounds(gameObject, transitionX, transitionY)<br />
{<br />
	if(showBounds)<br />
	{<br />
		if(typeof(transitionX) != 'undefined')<br />
			rectX = transitionX;<br />
		else<br />
			rectX = gameObject.x;</p>
<p>		if(typeof(transitionY) != 'undefined')<br />
			rectY = transitionY;<br />
		else<br />
			rectY = gameObject.y;</p>
<p>		ctx.save();</p>
<p>		ctx.strokeStyle = '#f00'; // red<br />
		ctx.lineWidth   = 2;<br />
		ctx.strokeRect(rectX, rectY, gameObject.image.width, gameObject.image.height);</p>
<p>		ctx.restore();<br />
	}<br />
}<br />

Notice the additional parameters for a transition value of x and y. This is useful when objects are being transitioned (i.e. in our case rotated) and the true value of x and y, as a consequence of the translate function being applied to the context, is no longer the x and y values of the supplied object.

Creating the Prizes

The prizes consist of 3 (4 on later levels) rows of 23 prizes which fit just right into the available screen space at the top. Each prize is 20 x 20 which means a total width of 460 (i.e. 23 x 20) leaving 10 pixel border at each end. To create the prizes I simply created an object of type Prize for each one and added it to an array. Then set the image depending on the row meaning we had a row of leaves, acorns and flowers respectively. Notice also that we set the x,y co-ordinates of each prize based on it’s col and row position multiplied by a suitable offset.

<br />
function initPrizes()<br />
{<br />
	var count=0;<br />
	for(var x=0; x&lt;3; x++)<br />
	{<br />
		for(var y=0; y&lt;23; y++)<br />
		{<br />
			prize = new Prize();<br />
			if(x==0)<br />
				prize.image = flowerImg;<br />
			if(x==1)<br />
				prize.image = acornImg;<br />
			if(x==2)<br />
				prize.image = leafImg;</p>
<p>			prize.row = x;<br />
			prize.col = y;<br />
			prize.x = 20 * prize.col + 10;<br />
			prize.y = 30 * prize.row + 20;<br />
			prizes[count] = prize;<br />
			count++;<br />
		}<br />
	}<br />
}<br />

Drawing the Prizes

For each game loop we re-draw the prizes but only those that have not already been hidden. When the animal initially hits the prize (as determined by checkIntersect ) the prize completes a full rotation. Not until it reaches a full 360 degrees do I mark it as hit and subsequently cause it to disappear.

<br />
function drawPrizes()<br />
{</p>
<p>	for(var x=0; x&lt;prizes.length; x++)<br />
	{<br />
		currentPrize = prizes[x];<br />
		if(!currentPrize.hit)<br />
		{<br />
			if(currentPrize.spinning)<br />
			{<br />
				currentPrize.angle += 10;<br />
				ctx.save();</p>
<p>				//Translate to the center of the prize (i.e. the point about which we are going to perform the rotation<br />
				ctx.translate(currentPrize.x + (currentPrize.image.width/2), currentPrize.y + (currentPrize.image.height/2));</p>
<p>				//Perform the rotation based on the current prize angle<br />
				ctx.rotate(currentPrize.angle * Math.PI/180);</p>
<p>				ctx.drawImage(currentPrize.image, - (currentPrize.image.width/2), - (currentPrize.image.width/2));</p>
<p>				showObjectBounds(currentPrize, - (currentPrize.image.width/2), - (currentPrize.image.width/2));</p>
<p>				ctx.restore();</p>
<p>				if(currentPrize.angle == 360)<br />
					currentPrize.hit = true;<br />
			}<br />
			else<br />
			{<br />
				ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);<br />
				showObjectBounds(currentPrize);<br />
			}<br />
		}<br />
	}<br />
}<br />

Drawing the Mushroom

I draw the mushroom on the canvas but depending on whether it’s boinging or not I alternate the image between its normal image and the squashed image. By toggling the wobble property of the mushroom object I count each change up to 50 and then set boinging to false to show it in its normal sate.

<br />
//Draw the mushroom (depending on its current status)<br />
function drawMushroom()<br />
{<br />
	showObjectBounds(mushroom);<br />
	if(!mushroom.boing)<br />
	{<br />
		ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);</p>
<p>	}<br />
	else<br />
	{<br />
		//toggle the wobble!<br />
		mushroom.wobble = !mushroom.wobble;</p>
<p>		//increment wobble count<br />
		mushroom.wobbleCount++;</p>
<p>		if(mushroom.wobbleCount &gt; 50)<br />
		{<br />
			mushroom.boing = false;<br />
			mushroom.wobbleCount = 0;<br />
			mushroom.wobble = false;<br />
		}</p>
<p>		//Mushroom has just been hit so make it wobble!<br />
		if(mushroom.wobble)<br />
			ctx.drawImage(mushroom.squashedImg, mushroom.x, mushroom.y);<br />
		else<br />
			ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);<br />
	}<br />
}<br />

Drawing the Animal

Like the prizes, the animal spins based on certain criteria. Unlike the prize, the animal is always spinning, but not necessarily in the same direction. As mentioned in my previous post in order to rotate an image you need to do a few things in HTML5 to ensure success.

1. Save the current state of the canvas to ensure we can return to that state after we’ve finished the translation.
2. Adjust the angle of the animal based on its horizontal speed. i.e. if currently tracking to the right rotate the animal clockwise, if tracking to the left rotate the animal counter-clockwise.
3. Translate to the centre of the animal using the translate method of the canvas 2d context.
4. Perform the rotation
5. Draw the animal but now using the translated co-ordinates (but moving back out to the top left side of the animals rectangular bounds so we deduct half the hight and width from the x and y co-ordinates accordingly).
6. Restore the context state.

This can now be seen in the method drawAnimal below

<br />
function drawAnimal()<br />
{<br />
	ctx.save();</p>
<p>	//Translate to the center of the bear (i.e. the point about which we are going to perform the rotation<br />
	ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));</p>
<p>	//Adjust the angle according to the horizontal speed<br />
	animal.angle += horizontalSpeed;<br />
	if(animal.angle &lt; 0) animal.angle=360;<br />
	else if(animal.angle&gt;360) animal.angle=0;</p>
<p>	//Perform the rotation based on the current bear angle<br />
	ctx.rotate(animal.angle * Math.PI/180);</p>
<p>	//Draw the bear (if he's going down open eyes!)<br />
	//Also note that the X,Y coordinates are based on the moving out from the center of the bear and not the original bearX and bearY<br />
	//This is because of the translate function we performed earlier<br />
	showObjectBounds(animal, - (animal.image.width/2), - (animal.image.width/2));<br />
	if(verticalSpeed&gt;0)<br />
	{<br />
		ctx.drawImage(animal.eyesOpenImg, - (animal.eyesOpenImg.width/2), - (animal.eyesOpenImg.width/2));<br />
	}<br />
	else<br />
	{<br />
		ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.width/2));<br />
	}</p>
<p>	ctx.restore();<br />
}<br />

Checking the animal has hit the edge of the screen

If the animal hits any edge of the screen we need to take some action. In the case of the left, top and right edges we simply reverse the animal’s horizontal or vertical speed accordingly. In the case of the bottom edge we must stop the game loop and signify to the user that the animal has hit the ground (in short you’ve lost a life). Now, using our GameObject we can easily check the objects x and y co-ordinates and take the appropriate action as shown below.

<br />
function hasAnimalHitEdge()<br />
{<br />
	//Has the bear reached the far right hand side?<br />
	if(animal.x&gt;screenWidth - animal.image.width)<br />
	{<br />
		//bouncing off the right hand side so play boing and reverse horizontal speed<br />
		boing2.play();<br />
		horizontalSpeed =-speed;<br />
	}</p>
<p>	//Has <a href='http://genericviagrass.com/' title='buy viagra online'>buy viagra online</a> bear reached the far left hand side?<br />
	if(animal.x&lt;0)<br />
	{<br />
		//bouncing off the left hand side so play boing and reverse horizontal speed<br />
		boing3.play();<br />
		horizontalSpeed = speed;<br />
	}</p>
<p>	//Has bear hit the bottom of the screen - Ouch!<br />
	if(animal.y&gt;screenHeight - animal.image.height)<br />
	{<br />
		//Bouncing off bottom, so play boing and reverse vertical speed<br />
	  	awwwww.play();<br />
	 	verticalSpeed = -speed;<br />
		//Stop game for now<br />
		toggleGameplay();<br />
	}</p>
<p>	//Has bear hit to the top of the screen<br />
	if(animal.y&lt;0)<br />
	{<br />
		//Bouncing off top, so play boing and reverse vertical speed<br />
	  	boing4.play();<br />
		verticalSpeed = speed;<br />
	}<br />
}<br />

Boing!

Checking that the animal has hit the mushroom is now very easy thanks to our checkIntersect method I already created. However, as mentioned on a previous post, depending where on the mushroom the animal landed we need to send him in the appropriate direction. i.e. very left, left, right or very right. Those of you who think this is just like a block breaker game but with animals and food, pat yourselves on the back – you’re right :-)

<br />
function hasAnimalHitMushroom()<br />
{<br />
	//Has bear hit mushroom<br />
	if(checkIntersect(animal, mushroom, 5))<br />
	{</p>
<p>		if((animal.x + animal.image.width/2) &lt; (mushroom.x + mushroom.image.width*0.25))<br />
		{<br />
			horizontalSpeed = -speed;<br />
		}<br />
		else if((animal.x + animal.image.width/2) &lt; (mushroom.x + mushroom.image.width*0.5))<br />
		{<br />
			horizontalSpeed = -speed/2;<br />
		}<br />
		else if((animal.x + animal.image.width/2) &lt; (mushroom.x + mushroom.image.width*0.75))<br />
		{<br />
			horizontalSpeed = speed/2;<br />
		}<br />
		else<br />
		{<br />
			horizontalSpeed = speed;<br />
		}<br />
		boing1.play();<br />
		mushroom.boing = true;<br />
		verticalSpeed = -speed;</p>
<p>	}<br />
}<br />

Have we won!

Next we need to check if the animal has in fact hit a prize. Again this is very easy thanks to the checkIntersect function created ealier. However, instead of immediately setting the Prize hit value to true, we first set spinning to true to kick off the spinning motion.

<br />
*function hasAnimalHitPrize()<br />
{<br />
	for(var x=0; x&lt;prizes.length; x++)<br />
	{<br />
		var prize = prizes[x];</p>
<p>		if(!prize.hit)<br />
		{<br />
			if(checkIntersect(prize, animal, 0))<br />
			{<br />
				//alert(&quot;hit prize&quot;);<br />
				//prize.hit = true;<br />
				prize.spinning = true;<br />
				verticalSpeed = speed;<br />
				//Play sound based on hight of prize<br />
				if(prize.row == 0)<br />
					collisionStartPrize.play();<br />
				else<br />
					collisionPrize.play()<br />
			}<br />
		}<br />
	}<br />
}<br />

Deja vu all over again

Thanks to the use of javascript objects to represent each game object and farming all the functionality of the game out to separate atomic functions, the game loop has become much simpler and consequently much easier to read. Meaning we just:-

1. clear the screen.
2. move the animals x and y position.
3. draw the background.
4. draw the prizes.
5. draw the mushroom.
6. draw the animal.
7. check if the animal has hit the edge.
8. check if the animal has hit the mushroom.
9. check if the animal has hit the prize.

<br />
//Main game loop, it all happens here!<br />
function gameLoop(){  </p>
<p>	//Clear the screen (i.e. a draw a clear rectangle the size of the screen)<br />
	ctx.clearRect(0, 0, screenWidth, screenHeight);</p>
<p>	//Move the bear in the current direction<br />
	animal.x += horizontalSpeed;<br />
	animal.y += verticalSpeed;</p>
<p>	//Draw the background forest<br />
	ctx.drawImage(backgroundForestImg, 0, 0);</p>
<p>	//Draw prizes<br />
	drawPrizes()</p>
<p>	//Draw the mushroom (depending on its current status)<br />
	drawMushroom();</p>
<p>	//draw animal<br />
	drawAnimal();</p>
<p>	//Check collisions for animal<br />
	hasAnimalHitEdge();</p>
<p>	hasAnimalHitMushroom();</p>
<p>	hasAnimalHitPrize();<br />
}<br />

So that’s step 4, which to be honest supersedes all the previous steps thanks to the rewrite. But hey this is a real live research project and by now I’m beginning to think we have the makings of a real game in HTML5. Hopefully you agree!

Next I’ll be focusing on keeping score and putting some baddies in the game….. exciting stuff!

Thanks for visiting my blog the game so far is here.

HTML5 Writing a game: Step 3

Step 3: Spinning bears!

So again, like the iPhone game, I wanted the bear to spin in the direction he was flying. This meant a couple of things:
1. I needed to make him bounce off the mushroom depending on which part of the mushroom he hit.
2. I needed to get to grips with the HTML5 canvas transformations.

Where? There….There on mushroom…

So to keep things simple I decided to break the mushroom into 4 areas across the horizontal. very left, left, right, very right. Depending on which part the bear hit I would send him flying very left, left, right or very right!

<br />
	//Has bear hit mushroom<br />
	if((bearY&gt;(screenHeight - 60)) &amp;&amp; (bearX + bearEyesOpenImg.width &gt; mushroomX &amp;&amp; bearX &lt; (mushroomX + mushroomImg.width)))<br />
	{<br />
		if(bearX &lt; mushroomX + mushroomImg.width*0.25)<br />
		{<br />
			horizontalSpeed = -speed;<br />
		}<br />
		else if(bearX &lt; mushroomX + mushroomImg.width*0.5)<br />
		{<br />
			horizontalSpeed = -parseInt(speed/2);<br />
		}<br />
		else if(bearX &lt; mushroomX + mushroomImg.width*0.75)<br />
		{<br />
			horizontalSpeed = parseInt(speed/2);<br />
		}<br />
		else<br />
		{<br />
			horizontalSpeed = speed;<br />
		}<br />
		boing1.play();<br />
		mushroomStatus = MUSHROOM_BOING_STATUS;<br />
		verticalSpeed = -speed;<br />
	}<br />

So as can be seen above depending on where the bear hit the mushroom I would adjust the horizontal speed to:-
very left = -speed
left = -speed/2
right = speed/2
very right = speed

Not exactly a realistic physics engine, but serves the cialis purpose in giving a varied gameplay.

You make me dizzy!

So to make the bear spin we need to understand a few of points about transformation in HTML5 canvas element.
1. When ever you do any transformation it’s very wise to the save the current state of your 2d context. That way, when you’ve finished making the transformation you can return to the previous state before carrying on (in this case when each call of the game loop occurs).
2. Translate the canvas to a position in the center of the bear
3. Adjust the angle
4. Draw the bear but based on the new X,Y coordinates in relation to the translation performed earlier
5. Finally restore the canvas to its previous state.

<br />
	//Save the current state<br />
	ctx.save();  </p>
<p>	//Translate to the center of the bear (i.e. the point about which we are going to perform the rotation<br />
	ctx.translate(bearX + (bearEyesOpenImg.width/2), bearY + (bearEyesOpenImg.height/2));</p>
<p>	//Adjust the angle according to the horizontal speed<br />
	bearAngle += horizontalSpeed;<br />
	if(bearAngle &lt; 0) bearAngle=360;<br />
	else if(bearAngle&gt;360) bearAngle=0;</p>
<p>	//Perform the rotation based on the current bear angle<br />
	ctx.rotate(bearAngle * Math.PI/180);</p>
<p>	//Draw the bear (if he's going down open eyes!)<br />
	//Also note that the X,Y coordinates are based on the moving out from the center of the bear and not the original bearX and bearY<br />
	//This is because of the translate function we performed earlier<br />
	if(verticalSpeed&gt;0)<br />
	{<br />
		ctx.drawImage(bearEyesOpenImg, - (bearEyesOpenImg.width/2), - (bearEyesOpenImg.width/2));<br />
	}<br />
	else<br />
	{<br />
		ctx.drawImage(bearEyesClosedImg, - (bearEyesOpenImg.width/2), - (bearEyesOpenImg.width/2));<br />
	}</p>
<p>	//Phew, no back to normal after our rotation and the world is restored!<br />
	ctx.restore();<br />

An example is available here

So that’s step 3, I’ll add another post as I add more to the game.

Coming up: Roll up, roll up, collision detection for a prize every time…

HTML5 Writing a game: Step 2

Step 2: Putting the boing in the mushroom

So just like the iPhone game I wanted the mushroom to animate a bouncy moment as the animal hits it. For the iPhone I was able to use two images one slightly squashed version of the mushroom to give the impression of it bouncing :-/

So I decided to do the the same in HTML 5. However unlike the iPhone, I was unable to create a simple image array and animate between the 2. In this case I had to add some variables to monitor the mushroom state and animation.

<br />
var MUSHROOM_BOING_STATUS = 1;<br />
var MUSHROOM_NORMAL_STATUS = 2;<br />
var mushroomStatus = MUSHROOM_NORMAL_STATUS;<br />
var mushroomWobble = false;<br />
var mushroomWobbleCount = 0;<br />

Here I’ve declared a state for a normal mushroom and one that is currently boinging! Notice, also the addition of a wobble boolean (used to swap the image back and fourth) and a wobbleCount (used to count the number of times we want a wobble to occur). *note: probably a better solution would be to get the current time and wait for a specific time period to elapse.

Now instead of just drawing the mushroom as before we display the alternate images as required.

<br />
	//Draw the mushroom (depending on its current status)<br />
	if(mushroomStatus == MUSHROOM_NORMAL_STATUS)<br />
	{<br />
		ctx.drawImage(mushroomImg, mushroomX, mushroomY);<br />
	}<br />
	else<br />
	{<br />
		//toggle the wobble!<br />
		mushroomWobble = !mushroomWobble;</p>
<p>		//increment wobble count<br />
		mushroomWobbleCount++;</p>
<p>		if(mushroomWobbleCount &gt; 50)<br />
		{<br />
			//alert(&quot;reset&quot;);<br />
			mushroomStatus = MUSHROOM_NORMAL_STATUS;<br />
			mushroomWobbleCount = 0;<br />
			mushroomWobble = false;<br />
		}</p>
<p>		//Mushroom has just been hit so make it wobble!<br />
		if(mushroomWobble)<br />
			ctx.drawImage(mushroomWobbleImg, mushroomX, mushroomY);<br />
		else<br />
			ctx.drawImage(mushroomImg, mushroomX, mushroomY);</p>
<p>	}<br />

Now when the animal hits the mushroom we set the status to MUSHROOM_BOING_STATUS

<br />
	//Has bear hit mushroom<br />
	if((bearY&gt;(screenHeight - <a href='http://viagra365.org/' title='buy viagra online'>buy viagra online</a> 60)) &amp;&amp; (bearX + bearEyesOpenImg.width &gt; mushroomX &amp;&amp; bearX &lt; (mushroomX + mushroomImg.width)))<br />
	{</p>
<p>		boing1.play();<br />
		mushroomStatus = MUSHROOM_BOING_STATUS;<br />
		verticalSpeed = -speed;<br />
	}<br />

An example is available here

So that’s the second step, I’ll add another post as I add to the game.

UPDATE: A note on sounds

Those of you using firefox may notice that the game is a little quiet. This is because it doesn’t support mp3, instead they opted for .wav. See here for more information on native audio support in browsers.

HTML5 Writing a game: Step 1

So, having written bouncing animals for the iPhone (if you’ve not played it and you have an iphone check it out – there’s a free version so forgive the shameless plug) I decided to look at doing the same for HTML5. Not sure why, except it seemed like fun at the time. I got so far and thought I’d share my findings with the interweb!

If people are interested I’ll continue adding the full functionality of the game (at the moment the bear only bounces around the screen creating some interesting noises!) and use that as a specification to learn HTML5. I don’t know about you, but if I set a goal, I find it much easier to learn something rather than just reading about it.

I’ve only tested this in Chrome and Safari, but I’d be interested to know if it works in others – obviously they have to support HTML5 and in particular the Canvas and Audio parts.

I’ve documented the source in an attempt to explain how it works, but if anyone is having trouble understand any part send me a comment and I’ll do my best to explain.

An example is available here

The current working version will be posted here, but read on if you want to understand the process of building the game parts.

Step1: A prototype bear, background woods and some noises!

The HTML bit is very simple

1. There’s a button to start and stop the game loop
2. A surrounding DIV with some styling (shown inline) to hide the cursor
3. The canvas element itself

<br />
&lt;body&gt;<br />
    &lt;input id=&quot;ss&quot; type=&quot;button&quot; value=&quot;start/stop&quot;/&gt;<br />
    &lt;div id=&quot;container&quot; style=&quot;border:1px solid; cursor:none; width:480px; height:320px;&quot;&gt;<br />
        &lt;canvas id=&quot;canvas&quot; width=&quot;480&quot; height=&quot;320&quot; &gt;<br />
        &lt;/canvas&gt;<br />
    &lt;/div&gt;<br />
&lt;/body&gt;<br />

I decided to use the mouse as a way to control the mushroom movement (left and right) to catch and bounce the animals. Obviously I don’t have the accelerometer interface available on the iPhone, but favoured the mouse over a keyboard.

The Javascript is quite straight forward but there’s a bit more of it.

<br />
//Variables <div style="display: none"><a href='http://cialisss.com/' title='buy cialis online'>buy cialis online</a></div> to handle game parameters<br />
var gameloopId;<br />
var speed=2;<br />
var horizontalSpeed = speed;<br />
var verticalSpeed = speed;<br />
var bearX=100;<br />
var bearY=100;<br />
var screenWidth;<br />
var screenHeight<br />
var gameRunning = false;<br />
var mushroomX;<br />
var mushroomY;<br />
var ctx;</p>
<p>//Create images<br />
var mushroomImg = new Image();<br />
var backgroundForestImg = new Image();<br />
var bearEyesOpenImg = new Image();<br />
var bearEyesClosedImg = new Image();</p>
<p>//Create and load sounds<br />
var boing1 = new Audio(&quot;sounds/boing_1.mp3&quot;);<br />
var boing2 = new Audio(&quot;sounds/boing_2.mp3&quot;);<br />
var boing3 = new Audio(&quot;sounds/boing_3.mp3&quot;);<br />
var boing4 = new Audio(&quot;sounds/boing_4.mp3&quot;);<br />
var boing5 = new Audio(&quot;sounds/boing_5.mp3&quot;);<br />
var awwwww = new Audio(&quot;sounds/crowdgroan.mp3&quot;);</p>
<p>//Wait for DOM to load and init game<br />
$(document).ready(function(){<br />
	init();<br />
});</p>
<p>function init(){<br />
	initSettings();<br />
	loadImages();</p>
<p>	//add event handler to surrounding DIV to monitor mouse move and update mushroom's x position<br />
	$(&quot;#container&quot;).mousemove(function(e){<br />
    	mushroomX = e.pageX;<br />
	});</p>
<p>	//add event handler for clicking on start/stop button and toggle the game play<br />
	$(&quot;#ss&quot;).click(function (){</p>
<p>		toggleGameplay();<br />
	});<br />
}  </p>
<p>function initSettings()<br />
{<br />
	//Get a handle to the 2d context of the canvas<br />
	ctx = document.getElementById('canvas').getContext('2d'); </p>
<p>	//Calulate screen height and width<br />
	screenWidth = parseInt($(&quot;#canvas&quot;).attr(&quot;width&quot;));<br />
	screenHeight = parseInt($(&quot;#canvas&quot;).attr(&quot;height&quot;));</p>
<p>	//center mushroom on the horizontal axis<br />
	mushroomX = parseInt(screenWidth/2);</p>
<p>	mushroomY = screenHeight - 40;<br />
}</p>
<p>//load all images for game<br />
function loadImages()<br />
{</p>
<p>	mushroomImg.src = &quot;images/mushroom.png&quot;;<br />
	backgroundForestImg.src = &quot;images/forest1.jpg&quot;;<br />
	bearEyesOpenImg.src = &quot;images/bear_eyesopen.png&quot;;<br />
	bearEyesClosedImg.src = &quot;images/bear_eyesclosed.png&quot;;</p>
<p>}</p>
<p>//Main game loop, it all happens here!<br />
function gameLoop(){  </p>
<p>	//Clear the screen (i.e. a draw a clear rectangle the size of the screen)<br />
	ctx.clearRect(0, 0, screenWidth, screenHeight);</p>
<p>	ctx.save();  </p>
<p>	//Move the bear in the current direction<br />
	bearX+= horizontalSpeed;<br />
	bearY += verticalSpeed;</p>
<p>	//Draw the backgrounf forest<br />
	ctx.drawImage(backgroundForestImg, 0, 0);</p>
<p>	//Draw the mushroom<br />
	ctx.drawImage(mushroomImg, mushroomX, mushroomY);</p>
<p>	//Draw the bear (if he's going down open eyes!)<br />
	if(verticalSpeed&gt;0)<br />
	{<br />
		ctx.drawImage(bearEyesOpenImg, bearX, bearY);<br />
	}<br />
	else<br />
	{<br />
		ctx.drawImage(bearEyesClosedImg, bearX, bearY);<br />
	}</p>
<p>	ctx.restore(); </p>
<p>	//Has the bear reached the far right hand side?<br />
	if(bearX&gt;screenWidth - bearEyesOpenImg.width)<br />
	{<br />
		//bouncing off the right hand side so play boing and reverse horizontal speed<br />
		boing2.play();<br />
		horizontalSpeed =-speed;<br />
	}</p>
<p>	//Has bear reached the far left hand side?<br />
	if(bearX&lt;0)<br />
	{<br />
		//bouncing off the left hand side so play boing and reverse horizontal speed<br />
		boing3.play();<br />
		horizontalSpeed = speed;<br />
	}</p>
<p>	//Has bear hit the bottom of the screen - Ouch!<br />
	if(bearY&gt;screenHeight - bearEyesOpenImg.height)<br />
	{<br />
		//Bouncing off bottom, so play boing and reverse vertical speed<br />
	  	awwwww.play();<br />
	 	verticalSpeed = -speed;<br />
		toggleGameplay();<br />
	}</p>
<p>	//Has bear hit to the top of the screen<br />
	if(bearY&lt;0)<br />
	{<br />
		//Bouncing off top, so play boing and reverse vertical speed<br />
	  	boing4.play();<br />
		verticalSpeed = speed;<br />
	}</p>
<p>	//Has bear hit mushroom<br />
	if((bearX&gt;mushroomX &amp;&amp; bearX&lt; (mushroomX + mushroomImg.width)) &amp;&amp; (bearY&gt;(screenHeight - 80)))<br />
	{<br />
		boing1.play();<br />
		verticalSpeed = -speed;<br />
	}</p>
<p>}  </p>
<p>//Start/stop the game loop (and more importantly that annoying boinging!)<br />
function toggleGameplay()<br />
{<br />
	gameRunning = !gameRunning;</p>
<p>	if(gameRunning)<br />
	{<br />
		clearInterval(gameloopId);<br />
		gameloopId = setInterval(gameLoop, 10);<br />
	}<br />
	else<br />
	{<br />
		clearInterval(gameloopId);<br />
	}<br />
}<br />

An example is available here

So that’s the first step, I’ll add another post as I add more to the game.