<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>indiegamr &#187; EaselJS</title>
	<atom:link href="http://indiegamr.com/category/easeljs/feed/" rel="self" type="application/rss+xml" />
	<link>http://indiegamr.com</link>
	<description>apps, indie &#38; beyond</description>
	<lastBuildDate>Sun, 30 Mar 2014 14:51:19 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.0.38</generator>
	<item>
		<title>SoundJS 0.5.2 Audio Plugin for CocoonJS 1.4.7</title>
		<link>http://indiegamr.com/soundjs-0-5-2-audio-plugin-for-cocoonjs-1-4-7/</link>
		<comments>http://indiegamr.com/soundjs-0-5-2-audio-plugin-for-cocoonjs-1-4-7/#comments</comments>
		<pubDate>Sun, 30 Mar 2014 14:45:36 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[audio]]></category>
		<category><![CDATA[CocoonJS]]></category>
		<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=739</guid>
		<description><![CDATA[I just updated the CocoonJSAudioPlugin.js to work with SoundJS 0.5.2 and CocoonJS 1.4.7 Download: CocoonJSAudioPlugin How to use: Just put the CocoonPlugin as the first entry to register and you can use everything else of the SoundJS-library just as is in &#8230; <a href="http://indiegamr.com/soundjs-0-5-2-audio-plugin-for-cocoonjs-1-4-7/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I just updated the CocoonJSAudioPlugin.js to work with SoundJS 0.5.2 and CocoonJS 1.4.7</p>
<p><strong>Download: <a href='http://indiegamr.com/wp-content/uploads/CocoonJSAudioPlugin_0.5.2.js'>CocoonJSAudioPlugin</a></strong></p>
<p><strong>How to use:</strong> Just put the CocoonPlugin as the first entry to register and you can use everything else of the SoundJS-library just as is in CocoonJS now.</p><pre class="crayon-plain-tag">createjs.Sound.registerPlugins([createjs.CocoonJSAudioPlugin]);</pre><p></p>
<hr />
<strong>Playing the same sound multiple times parallel/overlapping:</strong> You will have to set the maximum number of parallel sounds in the register-method:<br />
<pre class="crayon-plain-tag">//this will allow me to play 3 parallel instances of jump.ogg
  createjs.Sound.registerSound('jump.ogg','jump', 3);</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/soundjs-0-5-2-audio-plugin-for-cocoonjs-1-4-7/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Fading Waves Effect with EaselJS</title>
		<link>http://indiegamr.com/fading-line-effect-with-easeljs/</link>
		<comments>http://indiegamr.com/fading-line-effect-with-easeljs/#comments</comments>
		<pubDate>Wed, 15 May 2013 14:24:31 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=676</guid>
		<description><![CDATA[Today I made a basic JavaScript-version of my flash waves-effect, that I made a couple years back. direct link: http://labs.indiegamr.com/olines/index.html For bluring I used this filter: Link &#8211; but still: For those kind of operations HTML/JS is unfortunately still way &#8230; <a href="http://indiegamr.com/fading-line-effect-with-easeljs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Today I made a basic JavaScript-version of my <a href="http://activeden.net/item/owaves-wave-effect/full_screen_preview/124004">flash waves-effect</a>, that I made a couple years back.</p>
<p><iframe width="100%" height="250" scrolling="no" src="http://labs.indiegamr.com/olines/index.html"></iframe><br />
direct link: <a href="http://labs.indiegamr.com/olines/index.html">http://labs.indiegamr.com/olines/index.html</a></p>
<p>For bluring I used this filter: <a href="http://www.quasimondo.com/BoxBlurForCanvas/FastBlurDemo.html">Link</a> &#8211; but still: For those kind of operations HTML/JS is unfortunately still way behind flash in terms of performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/fading-line-effect-with-easeljs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Quickfix to enable touch of EaselJS-DisplayObjects in CocoonJS</title>
		<link>http://indiegamr.com/quickfix-to-enable-touch-of-easeljs-displayobjects-in-cocoonjs/</link>
		<comments>http://indiegamr.com/quickfix-to-enable-touch-of-easeljs-displayobjects-in-cocoonjs/#comments</comments>
		<pubDate>Sat, 16 Mar 2013 14:39:27 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[CocoonJS]]></category>
		<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=594</guid>
		<description><![CDATA[So while on the Stage touch is working for EaselJS in CocoonJS, it is currently not possible to touch individual EaselJS-DisplayObjects in CocoonJS. I wrote a quick fix for that, in case anyone else needs it. Download: easeljs_cocoonjs_touchfix.js (updated version to &#8230; <a href="http://indiegamr.com/quickfix-to-enable-touch-of-easeljs-displayobjects-in-cocoonjs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>So while on the Stage touch is working for EaselJS in CocoonJS, it is currently not possible to touch individual EaselJS-DisplayObjects in CocoonJS. I wrote a quick fix for that, in case anyone else needs it.</p>
<h2>Download: <a href="http://indiegamr.com/wp-content/uploads/easeljs_cocoonjs_touchfix.js">easeljs_cocoonjs_touchfix.js</a></h2>
<p> (updated version to work with EaselJS 0.7+, thx to Jonny)<br />
<strong>How to use:</strong> Download JS-fix and implement it through a script-tag somewhere after the EaselJS-script-tag and your done!</p>
<p>Hope this helps someone, comment for any issues,cheers!</p>
<p><small>If you use an older version of EaselJS: <a href="http://indiegamr.com/wp-content/uploads/easeljs_cocoonjs_touchfix_pre_0.7.js">easeljs_cocoonjs_touchfix_pre_0.7.js</a> (for pre-EaselJS 0.7)</small><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/quickfix-to-enable-touch-of-easeljs-displayobjects-in-cocoonjs/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>EaselJS CodeCompletion for SublimeText2</title>
		<link>http://indiegamr.com/easeljs-codecompletion-for-sublimetext2/</link>
		<comments>http://indiegamr.com/easeljs-codecompletion-for-sublimetext2/#comments</comments>
		<pubDate>Sat, 12 Jan 2013 11:20:13 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[SublimeText2]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=578</guid>
		<description><![CDATA[Today I was trying to scrape the EaselJS-Classes for their public methods and properties to generate an EaselJs-CodeCompletion for SublimeText2. I had some difficulties getting a unified set of information for each method/property because the code does not seem to &#8230; <a href="http://indiegamr.com/easeljs-codecompletion-for-sublimetext2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Today I was trying to scrape the EaselJS-Classes for their public methods and properties to generate an EaselJs-CodeCompletion for <a href="http://www.sublimetext.com/2" target="_blank">SublimeText2</a>. I had some difficulties getting a unified set of information for each method/property because the code does not seem to be consistently documenten. But well, here&#8217;s the result: It&#8217;s far from perfect but it works. Please feel free to fork it and help to make it better.</p>
<p><strong>Github: <a href="https://github.com/olsn/SublimeText2-EaselJS-Completion" target="_blank">https://github.com/olsn/SublimeText2-EaselJS-Completion</a></strong></p>
<p><strong>DemoImage: <a href="http://indiegamr.com/easeljs-codecompletion-for-sublimetext2/easel-completion-example/" rel="attachment wp-att-579"><img class="aligncenter size-full wp-image-579" title="easel-completion-example" src="http://indiegamr.com/wp-content/uploads/easel-completion-example.png" alt="" width="710" height="984" /></a></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/easeljs-codecompletion-for-sublimetext2/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>EaselJS Pixel Perfect Collision Detection for Bitmaps with Alpha Threshold</title>
		<link>http://indiegamr.com/easeljs-pixel-perfect-collision-detection-for-bitmaps-with-alpha-threshold/</link>
		<comments>http://indiegamr.com/easeljs-pixel-perfect-collision-detection-for-bitmaps-with-alpha-threshold/#comments</comments>
		<pubDate>Thu, 20 Dec 2012 05:24:10 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[gaming]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=558</guid>
		<description><![CDATA[I just finished the first version of a pixel perfect collision detection for EaselJS Bitmaps and BitmapAnimations. Get it from Github: https://github.com/olsn/Collision-Detection-for-EaselJS Here is an example (play around with the alpha threshold and toggle the detection mode): [crayon-69db7496c2eaa475579378/]]]></description>
				<content:encoded><![CDATA[<p>I just finished the first version of a pixel perfect collision detection for EaselJS Bitmaps and BitmapAnimations.<br />
<strong>Get it from Github: <a href="https://github.com/olsn/Collision-Detection-for-EaselJS" target="_blank">https://github.com/olsn/Collision-Detection-for-EaselJS</a></strong></p>
<p>Here is an example (play around with the alpha threshold and toggle the detection mode):<br />
<iframe width="320" height="240" style="width: 100%; height: 300px;" src="http://labs.indiegamr.com/easeljs_collision/"></iframe></p><pre class="crayon-plain-tag">// Rect Collision
var intersection = ndgmr.checkRectCollision(bitmap1,bitmap2);
// intersection is null if no collision, otherwise a {x,y,width,height}-Object is returned

// Pixel Perfect Collision
var collision = ndgmr.checkPixelCollision(bitmap1,bitmap2,alphaThreshold);
// true or false
// alphaThreshold default is 0, set to higher value to ignore collisions with semi transparent pixels</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/easeljs-pixel-perfect-collision-detection-for-bitmaps-with-alpha-threshold/feed/</wfw:commentRss>
		<slash:comments>59</slash:comments>
		</item>
		<item>
		<title>EaselJS 0.5.0</title>
		<link>http://indiegamr.com/easeljs-0-5-0/</link>
		<comments>http://indiegamr.com/easeljs-0-5-0/#comments</comments>
		<pubDate>Fri, 31 Aug 2012 18:44:50 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=457</guid>
		<description><![CDATA[I know it&#8217;s been out for a week now, but I guess I can still mention it: EaselJS 0.5.0 is out now: http://www.createjs.com/#!/EaselJS Check Out the Changelog here: https://github.com/CreateJS/EaselJS/blob/master/VERSIONS.txt]]></description>
				<content:encoded><![CDATA[<p>I know it&#8217;s been out for a week now, but I guess I can still mention it:<br />
EaselJS 0.5.0 is out now:<br />
<a href="http://www.createjs.com/#!/EaselJS" target="_blank">http://www.createjs.com/#!/EaselJS</a><br />
Check Out the Changelog here:<br />
<a href="https://github.com/CreateJS/EaselJS/blob/master/VERSIONS.txt" target="_blank">https://github.com/CreateJS/EaselJS/blob/master/VERSIONS.txt</a></p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/easeljs-0-5-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Retro Style Platform Runner Game for mobile with EaselJS (Part 5) – Animations and polishing</title>
		<link>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/</link>
		<comments>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/#comments</comments>
		<pubDate>Tue, 24 Jul 2012 06:44:47 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=366</guid>
		<description><![CDATA[In this 5th and for the moment last part of my series on creating an html5-canvas-game I&#8217;m going to write about adding animations and other elements to polish up the game a little bit. The result: Background Parallax So we&#8217;re &#8230; <a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In this 5th and for the moment last part of my series on creating an html5-canvas-game I&#8217;m going to write about adding animations and other elements to polish up the game a little bit.</p>
<p><strong>The result:</strong><br />
<iframe src="http://demos.indiegamr.com/jumpy/part5/index_d.html" width="100%" height="250"></iframe><br />
<span id="more-366"></span></p>
<h2>Background Parallax</h2>
<hr/>
So we&#8217;re going to start off with the background &#8211; at the moment it&#8217;s looking kinda pale and you cannot really see any movement. A background can contain pretty much anything that doesn&#8217;t distract the player from the game but is also not too boring. In this example I will just create a simple grid. Add the following to the jumpy.js:<br />
<pre class="crayon-plain-tag">self.createBgGrid = function(numX, numY) {
	var grid = new Container();
	grid.snapToPixel = true;
	// calculating the distance between
	// the grid-lines
	var gw = w/numX;
	var gh = h/numY;
	// drawing the vertical line
	var verticalLine = new Graphics();
	verticalLine.beginFill(Graphics.getRGB(101, 60, 176));
	verticalLine.drawRect(0,0,gw * 0.02,gh*(numY+2));
	var vs;
	// placing the vertical lines:
	// we're placing 1 more than requested
	// to have seamless scrolling later
	for ( var c = -1; c &lt; numX+1; c++) {
		vs = new Shape(verticalLine);
		vs.snapToPixel = true;
		vs.x = c * gw;
		vs.y = -gh;
		grid.addChild(vs);
	}
	// drawing a horizontal line
	var horizontalLine = new Graphics();
	horizontalLine.beginFill(Graphics.getRGB(101, 60, 176));
	horizontalLine.drawRect(0,0,gw*(numX+1),gh * 0.02);
	var hs;
	// placing the horizontal lines:
	// we're placing 1 more than requested
	// to have seamless scrolling later
	for ( c = -1; c &lt; numY+1; c++ ) {
		hs = new Shape(horizontalLine);
		hs.snapToPixel = true;
		hs.x = 0;
		hs.y = c * gh;
		grid.addChild(hs);
	}

	// return the grid-object
	return grid;
}</pre></p>
<p>And when the game is initialized, don&#8217;t forget to add the grid to the stage:</p><pre class="crayon-plain-tag">// setting up 'constants' for the number of vertical
// and horizontag background lines - play around with those values
var	GRID_HORIZONTAL = 8,
	GRID_VERTICAL = 4;

// and the following will be added to 'self.initializeGame'
background = self.createBgGrid(GRID_HORIZONTAL,GRID_VERTICAL);
stage.addChild(background);</pre><p></p>
<p>To emphasize movement we will make the background move with about 50% of the world-movement creating a <a href="http://en.wikipedia.org/wiki/Parallax" target="_blank">parallax-effect</a>. We accomplish that by adding the following to the &#8216;self.tick&#8217;-method:</p><pre class="crayon-plain-tag">// the background 'moves' about 45% of the speed of the world-object
// and it's position snaps back to zero once it's reached a limit 
background.x = (world.x * .45) % (w/GRID_HORIZONTAL); // horizontal
background.y = (world.y * .45) % (h/GRID_VERTICAL);   // vertical</pre><p></p>
<p><strong>Note:</strong> This is pretty much the most simple way to make a background move seamlessly as the world moves, however if you have a more complex background you will probably have to use either a greater modulo(%) or handle you background-movement individually.</p>
<p>The changes above should already result in something similar to this:<br />
<iframe src="http://demos.indiegamr.com/jumpy/part5/index_a.html" width="100%" height="250"></iframe><br />
Pretty simple &#8211; right? <img src="http://indiegamr.com/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley" /></p>
<h2>More Background Parallax</h2>
<hr/>
To add more motion to the scene we will create just a couple white lines in the background, that are supposed to symbolize distant waterfalls. To create such a waterfall-line, we add the following method to the jumpy.js:<br />
<pre class="crayon-plain-tag">self.createPixelLine = function(width) {
	// adjusting the width to the games scale
	// but not smaller than 1px and round it
	// to only have full pixels to render or
	// anti-aliasing will slow everything down
	width = Math.max(Math.round(width * scale),1);

	// drawing the line
	vl = new Graphics();
	vl.beginFill(Graphics.getRGB(255,255,255));
	vl.drawRect(0,0,width,h);

	lineShape = new Shape(vl);
	lineShape.snapToPixel = true;
	// the thinner the line, the less alpha
	// to make it look like it's further away
	lineShape.alpha = width * .25;
	// if it's further away, make it move slower
	lineShape.speedFactor = 0.3 + lineShape.alpha * 0.3 + Math.random() * 0.2;
	// the range defines when the line will be
	// moved back to the end of the screen
	lineShape.range = w + Math.random() * w * .3;
	// every line needs an offset, so they
	// don't start off at the same position
	lineShape.offsetX = Math.random() * w;
	
	return lineShape;
}</pre></p>
<p>And when we initialize the game, we will just create 4(or how many we want) of those lines:</p><pre class="crayon-plain-tag">// create and add another background-
// /parallax-layer
background_2 = new Container();
stage.addChild(background_2);
for ( var c = 0; c &lt; 4; c++) {
	// create a line/ distant waterfall
	var line = self.createPixelLine((Math.random()*3+1)|0);
	// add it to the scene
	background_2.addChild(line);
	// and push it to the parallaxObjects
	// don't forget to initialize that array
	parallaxObjects.push(line);
}</pre><p></p>
<p>And now we will make those lines move, just we like we made the grid move (it&#8217;s a little more complex this time, but the basic idea behind it, is the same):</p><pre class="crayon-plain-tag">l = parallaxObjects.length;
for ( c = 0; c &lt; l; c++ ) {
	p = parallaxObjects[c];
	// just change the x-coordinate
	// a change in the y-coordinate would not have any
	// result, since it's just a white line
	p.x = ((world.x * p.speedFactor - p.offsetX) % p.range) + p.range;
}</pre><p></p>
<p>And voila &#8211; now we got a pretty decent looking parallax-background already, of course with this way, it&#8217;s pretty simple to use just any graphic instead of white line, just add some vertcal-movement as well, and it should be good to go. The current result after adding all parallax elements looks like this:<br />
<iframe src="http://demos.indiegamr.com/jumpy/part5/index_b.html" width="100%" height="250"></iframe></p>
<h2>Animations</h2>
<hr/>
Now we will bring some more life into the scene by adding some animations, starting with some waterfalls. The key to animations in EaselJS is pretty much the same like most other engines and platforms: SpriteSheets. A SpriteSheet is a graphic that contains all frames of the animation as stills. This is how the SpriteSheets of the waterfall, we are going to use, looks, it contains 3 frames:
<p><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/waterfall2/" rel="attachment wp-att-385"><img src="http://indiegamr.com/wp-content/uploads/waterfall2.png" alt="" title="waterfall2" width="24" height="256" class="aligncenter size-full wp-image-385" /></a></p>
<p>The basic way for creating a SpriteSheet-Animation in EaselJS looks like this:</p><pre class="crayon-plain-tag">// defining the spriteSheetData
// this whole object can also be
// stored in a JSON-file, however
// by resizing my assets with my
// custom algorithm this would make
// things more complicated
var waterFallSpriteSheetData = {
	images: [assets[WATERFALL_IMAGE]],
	frames: {
		// dimensions of the animation
		height: 256 * scale,
		width: 8 * scale,
		// number of frames
		count: 3
	},
	animations: {
		// we call this animation 'default'
		default: {
			// it contains all 3 frames
			frames:[0, 1, 2],
			// and it runs with a decent speed
			frequency: 5
		}
	}
}
// ...

// and now we can initialize an animation at any time
var spriteSheet = new SpriteSheet(waterFallSpriteSheetData);
var waterfall = new BitmapAnimation(spriteSheet);
waterfall.snapToPixel = true;
waterfall.gotoAndPlay('default');</pre><p></p>
<p><strong>CAUTION:</strong> EaselJS version 0.4.2 does <strong>NOT</strong> support Canvas-Elements in SpriteSheets, however our scaling-algorithm creates a Canvas-Element, meaning that we have to UPDATE our version of EaselJS &#8211; you can download the &#8220;NEXT-Version&#8221; on <a href="https://github.com/CreateJS/EaselJS" target="_blank">github.com/CreateJS/EaselJS</a> &#8211; However, be aware, that this version uses namespacing, the simplest fix to get our game running with the &#8220;NEXT-Version&#8221; is to add the following into our index.html BEFORE loading EaselJS:</p><pre class="crayon-plain-tag">&lt;script&gt;
	var createjs = window;
&lt;/script&gt;
&lt;!-- now your can load the rest --&gt;
&lt;script src=&quot;js/easeljs-NEXT.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/utils.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/hero.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/jumpy.js&quot;&gt;&lt;/script&gt;</pre><p></p>
<p><strong>Note:</strong> The SpriteSheet-Data CAN also be stored and loaded from a JSON &#8211; but in this case the SpriteSheet-Data contans dynamic values, like the size and the image, that&#8217;s why I prefer to just initialize the whole thing within a JS method. For a more detailed view on all the possible attributes of a SpriteSheet, please refer to: <a href="http://createjs.com/Docs/EaselJS/SpriteSheet.html" target="_blank">http://createjs.com/Docs/EaselJS/SpriteSheet.html</a>.</p>
<p>As my next step I created a new layer in the front to add the waterfalls to and added a method that would add a waterfall to every platform with a probability of 35%. Since this is just placing and moving objects, I&#8217;m not going into detail about what lines of code I added where &#8211; for details please download and view the <a href="http://demos.indiegamr.com/jumpy/part5/part5.zip">sourcecode</a>.<br />
<iframe src="http://demos.indiegamr.com/jumpy/part5/index_c.html" width="100%" height="250"></iframe></p>
<p>As a final step I then added a fly to fly around our hero, it&#8217;s based on a simple 2-frame animation, and its movement is the following:</p><pre class="crayon-plain-tag">// the movement of the fly
// calculate an offset to create a &quot;swirling-like&quot; behaviour
fly.offsetX = ( Math.cos(ticks/10) * 10) * scale;
fly.offsetY = ( Math.sin(ticks/ 7) *  5) * scale;
// smoothly follow the hero by 10% of the distance every frame
fly.x = fly.x + (hero.x - fly.x) * .1 + fly.offsetX;
fly.y = fly.y + (hero.y - fly.y) * .1 + fly.offsetY;</pre><p></p>
<p><iframe src="http://demos.indiegamr.com/jumpy/part5/index_d.html" width="100%" height="250"></iframe></p>
<hr/>
<strong>And as allways: Download the <a href="http://demos.indiegamr.com/jumpy/part5/part5.zip">source</a>.</strong></p>
<hr/>
<strong>Agenda</strong></p>
<ul>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/">Part 1: User-Input (Keystrokes, MouseClick, Touch)  &amp; Movement</a></li>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/">Part 2: Collisions between objects</a></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/">Part 3: Movement&#038;More Collision</a></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays/">Part 4: Adjustments for mobile devices</a></li>
<li><strong>Part 5: Polishing up the game with animations &#038; eye candy</strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Retro Style Platform Runner Game for mobile with EaselJS (Part 4) – adjusting to mobile displays</title>
		<link>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays/</link>
		<comments>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays/#comments</comments>
		<pubDate>Wed, 18 Jul 2012 07:22:22 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=261</guid>
		<description><![CDATA[The 4th part of my series on creating an EaselJS-Game is about adjusting the game to different display-sizes, which is very important when targeting mobile devices. To visualize, what the result is going to look like &#8211; I added the &#8230; <a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The 4th part of my series on creating an EaselJS-Game is about adjusting the game to different display-sizes, which is very important when targeting mobile devices. To visualize, what the result is going to look like &#8211; I added the following two iframes, to demonstrate how the game adjusts to a different screen-/stage-size.</p>
<p><iframe width="100%" height="300" src="http://demos.indiegamr.com/jumpy/part4/index_nearestNeighbor.html"></iframe><br />
<br/>Open this <a href="http://demos.indiegamr.com/jumpy/part4/index_nearestNeighbor.html" target="_blank">http://demos.indiegamr.com/jumpy/part4/index_nearestNeighbor.html</a> in a new browser-window and see how it adjusts to your window-size as you reload the page after resizing the window.<br />
<span id="more-261"></span><br />
As allways: There are many ways to do this, all will pros and cons, I&#8217;m going to explain two (fairly simple) ways to do this.</p>
<h2>Method I &#8211; Linear Scaling: Easy&#038;straight forward</h2>
<hr/>
&#8216;Method I&#8217; basically consists of these two steps:</p>
<ol>
<li>Calculate the minimum-scale from the width&#038;height based on a default-width &#038; default hight</li>
<li>Multiply every (scale-relevant) value of the game with that scale(e.g: dimensions of objects, velocities, ect..)</li>
</ol>
<p>Calculating the scale is just one line: Okay in my case it&#8217;s 3, because I added variables for the default-dimensions:</p><pre class="crayon-plain-tag">/* defined globally */
var BASE_WIDTH = 800,
    BASE_HEIGHT = 400;
// this was new to me here: i tried using 'const' for those values, instead
// of 'var' which was working fine until i tried it with ...guess what: IE!

/* when initializing the _game() */
var w = getWidth(),
    h = getHeight(),
    scale = Math.min(w/BASE_WIDTH,h/BASE_HEIGHT);

// to make the scale accessbile from the 'outsite' through
// Game.scale, we assign it to the Game-object
self.scale = scale;</pre><p></p>
<p>So now that we have our scale-value: We are going to multiply every value, relevant to the scale, with it. As this involves quite a few parts of the code, instead of posting the whole updated source-code I&#8217;m going to list a few examples, and you can download the full source as always at the end of the page.</p><pre class="crayon-plain-tag">// e.g: when setting up the objects or position them
hero.x = 50 * scale;
hero.y = h/2 + 50 * scale;
hero.scaleX = hero.scaleY = scale;

// or when resetting attributes like velocity
Hero.prototype.reset = function() {
    this.velocity = {x:10*Game.scale,y:25*Game.scale};
    this.onGround = false;
    this.doubleJump = false;
};

// or when updating values
this.velocity.y += 1 * Game.scale;</pre><p></p>
<h2>Adjustments</h2>
<hr/>
However &#8211; we are not quite done by just multiplying all the values. Since we now <strong>(can) have decimal values</strong> for the width and height of all objects, we need to watch out for <strong>flaws in the collision detection</strong>: to prevent decimenal numbers from screwing with our collision detection, I added a parameter <span style="font-family:Courier;">&lt;rounded&gt;</span> to the utility-method <span style="font-family:Courier;">&#8216;getBounds()&#8217;</span>:<br />
<pre class="crayon-plain-tag">function getBounds(obj,rounded) {
  /* 
     I left out the calculation of the bounds, this is
     described in Part2
  */
  // and now round everything to get integer values
  if ( rounded ) {
    bounds.x = (bounds.x + (bounds.x &gt; 0 ? .5 : -.5)) | 0;
    bounds.y = (bounds.y + (bounds.y &gt; 0 ? .5 : -.5)) | 0;
    bounds.width = (bounds.width + (bounds.width &gt; 0 ? .5 : -.5)) | 0;
    bounds.height = (bounds.height + (bounds.height &gt; 0 ? .5 : -.5)) | 0;
  }
  return bounds;
}</pre><br />
In case you are wondering, why I&#8217;m not using &#8220;Math.round()&#8221;: Rounding with <strong>bitwise operators</strong> is <strong>7-9x faster</strong> than using Math.round(): <a href="http://jsperf.com/math-round-vs-hack/3" target="_bank">jsperf round() vs. bitwise benchmark</a></p>
<p style="font-size: 80%; padding: 4px; background: #ddd; border: solid 1px #aaa;">You don&#8217;t have to fully understand bitwise operations, but as a basic fact you should know, that with any bitwise operation all decimals will be erased. However, for optimizing code it is <strong>allways helpfull</strong> to know how bitwise <a href="http://en.wikipedia.org/wiki/Bitwise_operation" target="_blank">works</a>!</p>
<p>So all values from the returned bounds-rectangle will be integer values, to prevent the method from not detecting a collision, but then moving the object for example 0.5px too far, thus creating a collision-situation.<br />
Rounding values like the position or the velocity of an object is in 90% of the cases a good thing to do, as it is basically impossible to spot a difference between rounded- and non-rounded pixel-values while it is (on most platforms) <a href="http://seb.ly/2011/02/html5-canvas-sprite-optimisation/" target="_blank">way faster for the canvas to render on pixel instead of subpixel values</a>. So: use integer-values or for EaselJS-Objects: <span style="font-family:Courier;">myObject.snapToPixel = true;</span> &#8211; it is faster and in most cases you won&#8217;t see the difference.</p>
<p>That&#8217;s it with <i>Method I</i> of adjusting a canvas-app to the screen-size, you might think: <i>&#8216;Looks good to me, why should I use anything else?!&#8217;</i> &#8211; here&#8217;s the reason: The following image shows two scaled versions of Method I and Method II &#8211; and since we are building a <strong>retro-/pixel-style</strong> game, guess which method we are going to use <img src="http://indiegamr.com/wp-includes/images/smilies/icon_wink.gif" alt=";-)" class="wp-smiley" /></p>
<p><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays/scaling/" rel="attachment wp-att-303"><img src="http://indiegamr.com/wp-content/uploads/scaling.jpg" alt="" title="scaling" width="600" height="300" class="aligncenter size-full wp-image-303" /></a></p>
<h2>Method II &#8211; Nearest Neighbor Scaling: keep hard pixel-edges</h2>
<hr/>
As there is (currently?) no reliable way to turn off anti aliasing, (actually there ARE <a href="http://stackoverflow.com/a/10525163/1518765" target="_blank">ways to do this</a>, but they won&#8217;t work across all browsers), we are going to use the following algorithm to scale each of our assets after they are done loading:<br />
<pre class="crayon-plain-tag">function nearestNeighborScale(img, scale)
{
  // to have a good looking scaling
  // we will snap all values to 0.5-steps
  // so 1.4 e.g. becomes 1.5 - you can also
  // set the snapping to 1.0 e.g.
  // however I would recommend to use only 
  // a multiple of 0.5 - but play around
  // with it and see the results
  scale = snapValue(scale,.5);
  if ( scale <= 0 ) scale = 0.5;

  // the size of the "pixels" in the new images
  // will be rounden to integer values, as drawing
  // a rect with 1.5x1.5 would result in half-transparent
  // areas
  var pixelSize = (scale+0.99) | 0;

  // getting the data-array containing all the pixel-data
  // from our source-image
  var src_canvas = document.createElement('canvas');
  src_canvas.width = img.width;
  src_canvas.height = img.height;
  var src_ctx = src_canvas.getContext('2d');
  src_ctx.drawImage(img, 0, 0);
  var src_data = src_ctx.getImageData(0, 0, img.width, img.height).data;
  
  // setting up the new, scaled image
  var dst_canvas = document.createElement('canvas');
  // just to be sure, that no pixel gets lost, when
  // we scale the image down, we add 1 and floor the
  // result
  dst_canvas.width = (img.width * scale+1) | 0;
  dst_canvas.height = (img.height * scale+1) | 0;
  var dst_ctx = dst_canvas.getContext('2d');

  // reading each pixel-data from the source
  // and drawing a scaled version of that pixel
  // to the new canvas
  var offset = 0;
  for (var y = 0; y < img.height; ++y) {
      for (var x = 0; x < img.width; ++x) {
          var r = src_data[offset++];
          var g = src_data[offset++];
          var b = src_data[offset++];
          var a = src_data[offset++] / 255; // the alpha value needs to be divided
          dst_ctx.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
          dst_ctx.fillRect(x * scale, y * scale, pixelSize, pixelSize);
      }
  }

  return dst_canvas;
}

function snapValue(value,snap)
{
  var roundedSnap = (value/snap + (value > 0 ? .5 : -.5)) | 0;
  return roundedSnap * snap;
}</pre></p>
<p>So when the game gets initialized, we scale any bitmap loaded:</p><pre class="crayon-plain-tag">self.initializeGame = function() {
  assets[HERO_IMAGE] = nearestNeighborScale(assets[HERO_IMAGE], scale);
  assets[PLATFORM_IMAGE] = nearestNeighborScale(assets[PLATFORM_IMAGE], scale);
  // ...
  // see source for the rest of initializing part(no changes there)</pre><p></p>
<p>And then again, like with &#8216;Method I&#8217; we have to adjust every scale-relevant value, like velocities, positions <strong>EXCEPT</strong> for any scaleX or scaleY values, because our nearsetNeighborScale-method did that already. Also, just to be on the save side, we also do the collision-detection adjustments here (see bounds-rounding further up in the article).</p>
<h2>Compare both methods side by side</h2>
<hr/>
<div style="width: 100%;">
(both scales are limited to 0.5)</p>
<div style="width: 45%; float: left; padding: 3px; text-align: right; margin-left: auto;">
</iframe><iframe width="100%" height="150" src="http://demos.indiegamr.com/jumpy/part4/index_linearScale.html"></iframe><br />
<strong>Method I</strong><br />
  <span style="background:#aaffaa;">seamless scaling possible +</span><br />
  <span style="background:#ffaaaa;">image gets distorted on small scale -</span><br />
  <span style="background:#ffaaaa;">image gets blurry on big scale -</span>
</div>
<div style="width: 45%; float: left; border-left: 2px solid #000; padding: 3px;  margin-right: auto;">
</iframe><iframe width="100%" height="150" src="http://demos.indiegamr.com/jumpy/part4/index_nearestNeighbor.html"></iframe><br />
<strong>Method II</strong><br />
  <span style="background:#aaffaa;">+ no distortion, no blurryness</span><br />
  <span style="background:#ffaaaa;">- needs 0.5x values(0.5,1,1.5,2&#8230;)</span><br />
  <span style="background:#ffaaaa;">- only if retro-/pixel-effect is wanted</span>
</div>
<div style="clear:both;"></div>
</div>
<p><br/><br />
<strong>Download the sources: <a href="http://demos.indiegamr.com/jumpy/part4/part4.zip">here</a>.</strong></p>
<p><strong>Agenda</strong></p>
<ul>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/">Part 1: User-Input (Keystrokes, MouseClick, Touch)  &amp; Movement</a></li>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/">Part 2: Collisions between objects</a></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/">Part 3: Movement&#038;More Collision</a></li>
<li><strong>Part 4: Adjustments for mobile devices</strong></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/">Part 5: Polishing up the game with animations &#038; eye candy</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Retro Style Platform Runner Game for mobile with EaselJS (Part 3) &#8211; adding movement &amp; more collision</title>
		<link>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/</link>
		<comments>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/#comments</comments>
		<pubDate>Fri, 13 Jul 2012 10:13:51 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=226</guid>
		<description><![CDATA[So this is going to be Part3 of my series on creating a retro style platform runner game for mobile devices. Originally I wanted to write about adding animations in this part, however I rethought the who whole part and &#8230; <a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>So this is going to be Part3 of my series on creating a retro style platform runner game for mobile devices. Originally I wanted to write about adding animations in this part, however I rethought the who whole part and find it more suitable to first add some movement and make the collision detection complete, as it is still just a very basic algorithm in the <a title="Retro Style Platform Runner Game for mobile with EaselJS (Part 2)" href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/" target="_blank">previous part</a>.</p>
<p><strong>So this is going to be the result of this part:</strong><br />
<iframe src="http://demos.indiegamr.com/jumpy/part3/index.html" height="500" width="100%"></iframe><br />
<span id="more-226"></span></p>
<h2>Refining the collision detection</h2>
<hr />
<p>Even though the collision detection works fine with one other object, there are some flaws that you will notice when adding more than one object the hero can collide with. So for example in the last part I described how we can prevent the hero from &#8220;ghosting through&#8221; an obstacle when he&#8217;s going really fast &#8211; and the described way to check this works fine, so I checked if the hero&#8217;s y-position changes to the other side of the obstacle without him detecting a collision &#8211; however what I forgot to check there was whether the hero was even  on the same x-position as the obstacle. I now created a new method for the utils-class called &#8216;calculateCollision&#8217;, that I will also use for calculating horizontal collisions later:</p><pre class="crayon-plain-tag">function calculateCollision(obj, direction, collideables, moveBy)
{
      moveBy = moveBy || {x:0,y:0};
      if ( direction != 'x' &amp;&amp; direction != 'y' ) {
        direction = 'x';
      }
      var measure = direction == 'x' ? 'width' : 'height',
        oppositeDirection = direction == 'x' ? 'y' : 'x',
        oppositeMeasure = direction == 'x' ? 'height' : 'width',

        bounds = getBounds(obj),
        cbounds,
        collision = null,
        cc = 0;

    // for each collideable object we will calculate the
    // bounding-rectangle and then check for an intersection
    // of the hero's future position's bounding-rectangle
    while ( !collision &amp;&amp; cc &lt; collideables.length ) {
      cbounds = getBounds(collideables[cc]);
      if ( collideables[cc].isVisible ) {
        collision = calculateIntersection(bounds, cbounds, moveBy.x, moveBy.y);
      }

      if ( !collision &amp;&amp; collideables[cc].isVisible ) {
        // if there was NO collision detected, but somehow
        // the hero got onto the &quot;other side&quot; of an object (high velocity e.g.),
        // then we will detect this here, and adjust the velocity according to
        // it to prevent the Hero from &quot;ghosting&quot; through objects
        // try messing with the 'this.velocity = {x:0,y:125};'
        // -&gt; it should still collide even with very high values
        var wentThroughForwards  = ( bounds[direction] &lt; cbounds[direction] &amp;&amp; bounds[direction] + moveBy[direction] &gt; cbounds[direction] ),
          wentThroughBackwards = ( bounds[direction] &gt; cbounds[direction] &amp;&amp; bounds[direction] + moveBy[direction] &lt; cbounds[direction] ),
          withinOppositeBounds = !(bounds[oppositeDirection]+bounds[oppositeMeasure] &lt; cbounds[oppositeDirection])
                    &amp;&amp; !(bounds[oppositeDirection] &gt; cbounds[oppositeDirection]+cbounds[oppositeMeasure]);

        if ( (wentThroughForwards || wentThroughBackwards) &amp;&amp; withinOppositeBounds ) {
          moveBy[direction] = cbounds[direction] - bounds[direction];
        } else {
          cc++;
        }
      }
    }

    if ( collision ) {
      var sign = Math.abs(moveBy[direction]) / moveBy[direction];
      moveBy[direction] -= collision[measure] * sign;
    }

    return collision;
}</pre><p>&nbsp;<br />
I won&#8217;t go much into detail about the method, as there is just one major change, beside the fix of &#8220;ghosting&#8221; that I mentioned above: The method now takes care of the &#8216;moveBy&#8217; object, e.g.: If your hero wants to <strong>move by <span style="font-family:Courier;">{x:0, y:15}</span></strong> and there is a collision detected at y=5, the method changes the <strong>move by to <span style="font-family:Courier;">{x:0, y:5}</span></strong> so you allways automatically know how far you can move the hero until it collides.<br />
This makes the hero&#8217;s tick-method a lot cleaner:</p><pre class="crayon-plain-tag">Hero.prototype.tick = function () {
	this.velocity.y += 1;

	var moveBy = {x:0, y:this.velocity.y},
		collision = null,
		collideables = Game.getCollideables();

	collision = calculateCollision(this, 'y', collideables, moveBy);
	// moveBy is now handled by 'calculateCollision'
	// and can also be 0 - therefore we won't have to worry
	this.y += moveBy.y;

	if ( !collision ) {
		if ( this.onGround ) {
			this.onGround = false;
			this.doubleJump = true;
		}
	} else {
		// the hero can only be 'onGround'
		// when he's hitting floor and not
		// some ceiling
		if ( moveBy.y &gt; 0 ) {
			this.onGround = true;
			this.doubleJump = false;
		}
		this.velocity.y = 0;
	}
        // and now handle the x-movement
	moveBy = {x:this.velocity.x, y:0};
	collision = calculateCollision(this, 'x', collideables, moveBy);
	this.x += moveBy.x;
};</pre><p></p>
<h2>Movement</h2>
<hr/>
Adding movement is probably the most easiest thing to do here, just go to the initialize-method of the Hero-class and assign an x-value to the velocity property:<br />
<pre class="crayon-plain-tag">this.velocity = {x:10,y:25};</pre><br />
And because we already added the handling of the x-movement to the hero&#8217;s tick()-method, this is done. However if we look at the result, I guess it&#8217;s pretty obvious whats missing:<br />
<iframe src="http://demos.indiegamr.com/jumpy/part3/index_a.html" height="300" width="100%"></iframe></p>
<h2>We need more platforms!</h2>
<hr/>
So we already added one platform in the initializeGame-method, to add some more platform we just need to create a loop:<br />
<pre class="crayon-plain-tag">// add a platform for the hero to collide with
self.addPlatform(50 - assets[PLATFORM_IMAGE].width/2, h/1.25);

// the number of platforms to be added depends on the screen-width
var c, l = w / assets[PLATFORM_IMAGE].width * 1.5,
    atX=0,
    atY = h/1.25;

for ( c = 1; c &lt; l; c++ ) {
	// define a random x-koordinate relative to the last one
	var atX = (c-.5) * assets[PLATFORM_IMAGE].width*2 + (Math.random()*assets[PLATFORM_IMAGE].width-assets[PLATFORM_IMAGE].width/2);
	// define a random y-koordinate relative to the last one
	var atY = atY + Math.random() * 300 - 150;
	// add the platform
	self.addPlatform(atX,atY);
}</pre></p>
<p>Now that we&#8217;ve added all the platform, we can jump around, however our hero still keeps running out of the view, to follow the hero with the camera, we simply reposition the &#8220;world&#8221; every frame according to the hero&#8217;s position &#8211; add this to the main-tick-method:</p><pre class="crayon-plain-tag">// if the hero &quot;leaves&quot; it's bounds of
// screenWidth * 0.3 and screenHeight * 0.3(to both ends)
// we will reposition the &quot;world-container&quot;, so our hero
// is allways visible
if ( hero.x &gt; w*.3 ) {
	world.x = -hero.x + w*.3;
}
if ( hero.y &gt; h*.7 ) {
	world.y = -hero.y + h*.7;
} else if ( hero.y &lt; h*.3 ) {
	world.y = -hero.y + h*.3;
}</pre><p></p>
<p>Now we have: a few platforms, the &#8220;camera&#8221; following our hero, but the course is not infinite yet!<br />
There are a quite a few ways to make the course infinite, I&#8217;m just going to describe one: Since the hero cannot walk to the left, everything to the left of the visible screen can be &#8220;thrown&#8221; away, since it won&#8217;t become visible again! &#8211; However we are not going to throw away the platform that move out of the screen, we are just going to reposition them at the end of the track:<br />
<a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/infinite/" rel="attachment wp-att-242"><img src="http://indiegamr.com/wp-content/uploads/infinite.jpg" alt="" title="infinite" width="600" height="300" class="aligncenter size-full wp-image-242" /></a></p>
<p>So in the jumpy.js with every tick() we also execute this check:</p><pre class="crayon-plain-tag">for ( var c = 0; c &lt; collideables.length;; c++ ) {
	var p = collideables[c];
	if ( p.localToGlobal(p.image.width,0).x &lt; -10 ) {
		self.movePlatformToEnd(p);
	}
}</pre><p></p>
<p>and then we of course need to define the method &#8220;movePlatformToEnd()&#8221;:</p><pre class="crayon-plain-tag">self.movePlatformToEnd = function(platform) {
	platform.x = self.lastPlatform.x + platform.image.width*2 + Math.random()*platform.image.width*2 - platform.image.width;
	platform.y = self.lastPlatform.y + Math.random() * 300 - 150;
	self.lastPlatform = platform;
}</pre><p></p>
<p>As you can see &#8211; the platform will be positioned according to the &#8220;lastPlatform&#8217;s&#8221; position and then made the &#8216;lastPlatform&#8217; itself &#8211; so when we first create all the platforms with &#8216;addPlatform()&#8217; we also have to add this last line <span style="font-family:Courier;">self.lastPlatform = platform;</span>.</p>
<p>And that&#8217;s pretty much it &#8211; to round everything up, you can add a &#8220;reset()&#8221; method &#8211; to reset everything once the hero drops below a certain y-koordinate for example. Such a method should be rather trivial, so I&#8217;m not gonna go into detail here but I implemented such a method, so checkout the sources if you want to take a look at it.</p>
<p><strong>Download the sources: <a href="http://demos.indiegamr.com/jumpy/part3/part3.zip">here</a>.</strong></p>
<hr />
<p><strong>Agenda</strong></p>
<ul>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/">Part 1: User-Input (Keystrokes, MouseClick, Touch)  &amp; Movement</a></li>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/">Part 2: Collisions between objects</a></li>
<li><strong>Part 3: Movement&#038;More Collision</strong></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays">Part 4: Adjustments for mobile devices</a></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/">Part 5: Polishing up the game with animations &#038; eye candy</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Retro Style Platform Runner Game for mobile with EaselJS (Part 2)</title>
		<link>http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/</link>
		<comments>http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/#comments</comments>
		<pubDate>Thu, 05 Jul 2012 12:26:44 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=154</guid>
		<description><![CDATA[This is Part 2 of my tutorial on How to create a Runner Game for mobile with EaselJS &#8211; in this part i&#8217;m going to cover the collision-detection between two objects in EaselJS. Types of Collision Detection There are several types &#8230; <a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This is Part 2 of my tutorial on <a title="Retro Style Plattform Runner Game for mobile with EaselJS (Part 1)" href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/">How to create a Runner Game for mobile with EaselJS</a> &#8211; in this part i&#8217;m going to cover the collision-detection between two objects in EaselJS.</p>
<h2>Types of Collision Detection</h2>
<hr />
<p>There are several types of collision detection methods, I&#8217;m going to explain two of the most commong ways to detect a collision &#8211; if you want more/detailed information on the subject I would encourage you to google for it or try this <a href="http://www.wildbunny.co.uk/blog/2011/04/20/collision-detection-for-dummies/" target="_blank">article</a> as an introduction to the topic.</p>
<p><strong>1) Distance Based- or Circle-Collision</strong></p>
<p>This is probably the simplest type of collision detection. What you basically have to do is to set a collision-radius for each object, then calculate the distance between the objects and see if the distrance is lower than the radii combined. However the following image shows, that this kind of detection won&#8217;t be suitable for our platform game:</p>
<p><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/collision_1/" rel="attachment wp-att-157"><img class="aligncenter size-full wp-image-157" title="collision_1" src="http://indiegamr.com/wp-content/uploads/collision_1.jpg" alt="" width="300" height="300" /></a><br />
<span id="more-154"></span></p>
<p>As you can see, with this method, a collision is detected way before an actual collision occures. This is due to the fact, that the platform has a very different hight and width. However a circle-collision-detection would be perfect for any Pool-game for example.</p>
<p><strong>2) Bounding-Box-Collision</strong></p>
<p>This type of  detection is (is many cases, not all) more accurate than the circle-based detection and it basically works by defining a rectangle of the boundaries for each object and then check if those two rectangles intersect in any way.</p>
<p><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/collision_2a/" rel="attachment wp-att-200"><img class="aligncenter size-full wp-image-200" title="collision_2a" src="http://indiegamr.com/wp-content/uploads/collision_2a.jpg" alt="" width="300" height="300" /></a></p>
<p>There are two(or probably more, but i&#8217;m only going to point out two of them) ways to collect a collision this way.</p>
<p>The first method is actually not checking for a collision, but for non-collisions. This simply requires four if clauses:</p>
<ul>
<li>a) is the space between rect1.left and rect2.right ?</li>
<li>b) is there space between rect1.right and rect2.left ?</li>
<li>c) is there space between rect1.top and rect2.bottom ?</li>
<li>d) is there space between rect1.bottom and rect2.top ?</li>
</ul>
<p>If any (1 or more) of the statements above are true, then there is no intersection between the rectangles, however if all of the statements are false, there must be an intersection.</p>
<p>And here is the according piece of code:</p><pre class="crayon-plain-tag">function checkRectIntersection(rect1,rect2) {
  if ( rect1.x &amp;gt;= rect2.x + rect2.width    // a)
    || rect1.x + rect1.width &amp;lt;= rect2.x    // b)
    || rect1.y &amp;gt;= rect2.y + rect2.height   // c)
    || rect1.y + rect1.height &amp;lt;= rect2.y ) // d)
      return false;

  return true;
};</pre><p>Even though this method looks super-simple &#8211; we are unfortunately <strong>NOT</strong> going to use this method. Instead we will use a method that checks for an intersection AND returns the size of the intersecting area.</p>
<p>To explain this a little better i drew up a graphic for this:</p>
<p><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/collision_2c/" rel="attachment wp-att-171"><img class="aligncenter size-full wp-image-171" title="collision_2c" src="http://indiegamr.com/wp-content/uploads/collision_2c.jpg" alt="" width="300" height="300" /></a></p>
<p>So what we are going to do, is calculate the X- and the Y-overlapping value, if both values are greater than 0, there is an intersecting area.</p><pre class="crayon-plain-tag">dx = |cx1 - cx2| - (hw1 + hw2)
dy = |cy1 - cy2| - (hh1 + hh2)</pre><p>=&gt; if  d<sub>x</sub> &lt; 0 and d<sub>y </sub>&lt; 0 then there is a collision, in this case we can return -d<sub>x</sub> and -d<sub>y</sub> as overlapping values</p>
<p>And the method in JS looks like this &#8211; I also added two parameters x and y, to calculate where the rect1 wants to move to:</p><pre class="crayon-plain-tag">function calculateIntersection(rect1, rect2, x, y) {
  // prevent x|y from being null||undefined
  x = x || 0; y = y || 0;

  // first we have to calculate the
  // center of each rectangle and half of
  // width and height
  var dx, dy, r1={}, r2={};
  r1.cx = rect1.x+x+(r1.hw = (rect1.width /2));
  r1.cy = rect1.y+y+(r1.hh = (rect1.height/2));
  r2.cx = rect2.x + (r2.hw = (rect2.width /2));
  r2.cy = rect2.y + (r2.hh = (rect2.height/2));

  dx = Math.abs(r1.cx-r2.cx) - (r1.hw + r2.hw);
  dy = Math.abs(r1.cy-r2.cy) - (r1.hh + r2.hh);

  if (dx &amp;lt; 0 &amp;amp;&amp;amp; dy &amp;lt; 0) {
    return {width:-dx,height:-dy};
  } else {
    return null;
  }
}</pre><p>This is also the method we are going to use in the game. There are plenty of other methods that are probably more accurate(a mix of Circle/BoundBox-collision, Pixel-perfect collision ect.), but <span style="text-decoration: underline;">usually take longer for their calculation</span>. And for the sake of keeping everything simple our current method will do a pretty good job and you won&#8217;t really notice any flaws of the collisions in the game. I could spend a lot more time on figuring out a pixel-perfect collision algorithm ect., just to get rid of the last &#8220;free spaces&#8221; &#8211; however it won&#8217;t look that much more realistic to be worth the effort. This is actually a good tipp for new game-developers:</p>
<p><span style="color: #333333;"><strong>Go with simple!:<br />
</strong></span><span style="color: #333333;">In </span><strong style="color: #333333;">90%</strong><span style="color: #333333;"> of the cases a </span><strong style="color: #333333;">simple version works just</strong><span style="color: #333333;"> (almost) </span><strong style="color: #333333;">as good</strong><span style="color: #333333;"> as a &#8216;perfect&#8217; version, that would have taken much much longer to develop. The same with making a method as universial as possible because you say &#8220;I might need it later for something else&#8221; &#8211; there&#8217;s a </span><strong style="color: #333333;">very</strong><span style="color: #333333;"> good chance, that you will </span><strong style="color: #333333;">not need it</strong><span style="color: #333333;">- and if you do: Do it when you need it, you won&#8217;t loose any time.</span></p>
<p>So now we&#8217;ve got our collision-method &#8211; how do we use it in the game?</p>
<h2>Implementation</h2>
<hr />
<p>Before we can acutally use the detection-method in the game, we need the bounding rectangle of our EaselJS DisplayObject &#8211; however since EaselJS is not providing such a function(yet?), we will use <a title="getBounds() method for EaselJS DisplayObjects" href="http://indiegamr.com/getbounds-method-for-easeljs-displayobjects/">the method from here</a> and put it into our utils.js(included in the <a href="http://demos.indiegamr.com/jumpy/part1/part1.zip" target="_blank">zip-file</a> from<a title="Retro Style Plattform Runner Game for mobile with EaselJS (Part 1)" href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/"> Part 1</a>) as well as the &#8220;calculateIntersection()&#8221; method.</p>
<p>We then will update the tick-method of our Hero-class with the following:</p><pre class="crayon-plain-tag">Hero.prototype.tick = function () {
    this.velocity.y += 1;

    // preparing the variables
    var c = 0,
        cc = 0,
        addY = this.velocity.y,
        bounds = getBounds(this),
        cbounds,
        collision = null,
        collideables = Game.getCollideables();

    cc=0;
    // for each collideable object we will calculate the
    // bounding-rectangle and then check for an intersection
    // of the hero's future position's bounding-rectangle
    while ( !collision &amp;amp;&amp;amp; cc &amp;lt; collideables.length ) {
			cbounds = getBounds(collideables[cc]);
			if ( collideables[cc].isVisible ) {
				collision = calculateIntersection(bounds, cbounds, 0, addY);
			}

			if ( !collision &amp;amp;&amp;amp; collideables[cc].isVisible ) {
				// if there was NO collision detected, but somehow
				// the hero got onto the &quot;other side&quot; of an object (high velocity e.g.),
				// then we will detect this here, and adjust the velocity according to
				// it to prevent the Hero from &quot;ghosting&quot; through objects
				// try messing with the 'this.velocity = {x:0,y:25};'
				// -&amp;gt; it should still collide even with very high values
				if ( ( bounds.y &amp;lt; cbounds.y &amp;amp;&amp;amp; bounds.y + addY &amp;gt; cbounds.y )
				  || ( bounds.y &amp;gt; cbounds.y &amp;amp;&amp;amp; bounds.y + addY &amp;lt; cbounds.y ) ) {
					addY = cbounds.y - bounds.y;
				} else {
					cc++;
				}
			}
		}

    // if no collision was to be found, just
    // move the hero to it's new position
    if ( !collision ) {
        this.y += addY;
        if ( this.onGround ) {
            this.onGround = false;
            this.doubleJump = true;
        }
    // else move the hero as far as possible
    // and then make it stop and tell the
    // game, that the hero is now &quot;an the ground&quot;
    } else {
        this.y += addY - collision.height;
        if ( addY &amp;gt; 0 ) {
            this.onGround = true;
            this.doubleJump = false;
        }
        this.velocity.y = 0;
    }
}</pre><p>now we have to add a platform for the hero to collide with, I therefor create a method called &#8220;addPlatform&#8221;, that should mostly explain itself:</p><pre class="crayon-plain-tag">this.addPlatform = function(x,y) {
    x = Math.round(x);
    y = Math.round(y);

    var platform = new Bitmap(assets[PLATFORM_IMAGE]);
    platform.x = x;
    platform.y = y;
    platform.snapToPixel = true;

    world.addChild(platform);
    collideables.push(platform);
}</pre><p>also I did update the javascript-file holding the main methods and the game loop ect. quite a bit(to make the post not too big, I left out a few parts &#8211; download the <a href="http://demos.indiegamr.com/jumpy/part1/part2.zip">ZIP-file</a> to get the full source):</p><pre class="crayon-plain-tag">var  HERO_IMAGE = 'assets/hero.png',
     PLATFORM_IMAGE = 'assets/platform.png';

function _game()
{
    window.Game = this;
    var self = this, ticks = 0, canvas, stage, world, hero,
        w = getWidth(), h = getHeight(), assets = [], keyDown = false;

    // holds all collideable objects
    var collideables = [];
    this.getCollideables = function() { return collideables; };

    // starts to load all the assets
    this.preloadResources = function() {
        self.loadImage(HERO_IMAGE);
        self.loadImage(PLATFORM_IMAGE);
    }

    var requestedAssets = 0, loadedAssets = 0;
    // loads the assets and keeps track 
    // of how many assets where there to
    // be loaded
    this.loadImage = function(e) {
        var img = new Image();
        img.onload = self.onLoadedAsset;
        img.src = e;

        assets[e] = img;

        ++requestedAssets;
    }
    // each time an asset is loaded
    // check if all assets are complete
    // and initialize the game, if so
    this.onLoadedAsset = function(e) {
        ++loadedAssets;
        if ( loadedAssets == requestedAssets ) {
            self.initializeGame();
        }
    }

    this.initializeGame = function() {
        /* setting up stage&amp;amp;listeners - download ZIP */

        // creating the Hero, and assign an image
        // also position the hero in the middle of the screen
        hero = new Hero(assets[HERO_IMAGE]);
        hero.x = w/2
        hero.y = h/2;
        world.addChild(hero);

        // add a platform for the hero to collide with
        self.addPlatform(w/2 - assets[PLATFORM_IMAGE].width/2, h/1.25);
    }

    this.tick = function(e)
    {
        ticks++;
        hero.tick();
        stage.update();
    }

    // this method adds a platform at the
    // given x- and y-coordinates and adds
    // it to the collideables-array
    this.addPlatform = function(x,y) {
        x = Math.round(x);
        y = Math.round(y);

        var platform = new Bitmap(assets[PLATFORM_IMAGE]);
        platform.x = x;
        platform.y = y;
        platform.snapToPixel = true;

        world.addChild(platform);
        collideables.push(platform);
    }

    /* input-listeners - download ZIP */

    self.preloadResources();
};

new _game();</pre><p>When you try this out &#8211; it should look similar to this:</p>
<p><iframe width="100%" height="330" src="http://demos.indiegamr.com/jumpy/part1/"></iframe></p>
<p>Some of you might noticed that, the hero is also able to jump twice now: I removed the reset()-method from Hero.js and replaced it with a similar jump()-method:</p><pre class="crayon-plain-tag">Hero.prototype.jump = function() {
    // if the hero is &quot;on the ground&quot;
    // let him jump, physically correct!
    if ( this.onGround ) {
        this.velocity.y = -17;
        this.onGround = false;
        this.doubleJump = true;
    // we want the hero to be able to
    // jump once more when he is in the
    // air - after that, he has to wait
    // to lang somewhere on the ground
    } else if ( this.doubleJump ) {
        this.velocity.y = -17;
        this.doubleJump = false;
    }
}</pre><p>And that&#8217;s pretty much all there is to get a basic collision detection working &#8211; Again: There are PLENTY of other methods, some of them maybe better in performance and/or accuracy, however I find this approach to be both fairly simple, effective and easy to follow &#8211; but suggestions for different approaches are allways welcome, just leave a comment! <img src="http://indiegamr.com/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley" /></p>
<p>The sources for this part can be found right here: <a href="http://demos.indiegamr.com/jumpy/part1/part2.zip">Download Part2.zip</a></p>
<hr />
<p><strong>Agenda</strong></p>
<ul>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/" target="_blank">Part 1: User-Input (Keystrokes, MouseClick, Touch)  &amp; Movement</a></li>
<li><strong>Part 2: Collisions between objects</strong></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-3-adding-movement-more-collision/" target="_blank">Part 3: Movement&#038;More Collision</a></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-4-adjusting-to-mobile-displays">Part 4: Adjustments for mobile devices</a></li>
<li><a href="http://indiegamr.com/retro-style-platform-runner-game-for-mobile-with-easeljs-part-5-animations-and-polishing/">Part 5: Polishing up the game with animations &#038; eye candy</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
