<?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; mobile</title>
	<atom:link href="http://indiegamr.com/category/mobile/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>The state of Audio in HTML5 Games</title>
		<link>http://indiegamr.com/the-state-of-audio-in-html5-games/</link>
		<comments>http://indiegamr.com/the-state-of-audio-in-html5-games/#comments</comments>
		<pubDate>Fri, 26 Apr 2013 10:46:00 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[audio]]></category>
		<category><![CDATA[gaming]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=649</guid>
		<description><![CDATA[HTML5 Gaming for desktop and mobile is a very trendy topic these days. The performance of canvas applications is getting better and better each day and technologies like CocoonJS or Ejecta even enable a close to native performance for canvas &#8230; <a href="http://indiegamr.com/the-state-of-audio-in-html5-games/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p style="text-align: left;">HTML5 Gaming for desktop and mobile is a very trendy topic these days. The performance of canvas applications is getting better and better each day and technologies like <a href="http://ludei.com/tech/cocoonjs">CocoonJS</a> or <a href="http://impactjs.com/ejecta">Ejecta</a> even enable a close to native performance for canvas applications on mobile devices. &#8211; But what about audio? Is it really that easy to implement sound with your html app?<br />
This article features some interesting points that I collected while researching for my eBook ‘<a href="http://indiegamr.com/zerotoappstore/">From Zero to the Appstore’</a>.</p>
<h2>Audio != Audio</h2>
<p style="text-align: left;">While most browsers and devices already do support audio in general, that doesn’t mean you can just play any audio file in any modern browser. The following table briefly lists the support for Audio-codecs.</p>
<p><span id="more-649"></span></p>
<table style="font-size: 70%;" width="70%" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top"><strong>Browser</strong></td>
<td valign="top"><strong>Codec Support</strong></td>
</tr>
<tr>
<td valign="top"><strong>Chrome</strong></td>
<td valign="top">Ogg, MP3, WAV</td>
</tr>
<tr>
<td valign="top"><strong>Firefox</strong></td>
<td valign="top">Ogg, WAV</td>
</tr>
<tr>
<td valign="top"><strong>Internet Explorer (9+)</strong></td>
<td valign="top">MP3, AAC</td>
</tr>
<tr>
<td valign="top"><strong>Opera</strong></td>
<td valign="top">Ogg, WAV</td>
</tr>
<tr>
<td valign="top"><strong>Safari</strong></td>
<td valign="top">MP3, AAC, WAV</td>
</tr>
<tr>
<td valign="top"><strong> </strong></td>
<td valign="top"></td>
</tr>
<tr>
<td valign="top"><strong>Android</strong></td>
<td valign="top">Depending on the Device</td>
</tr>
<tr>
<td valign="top"><strong>Blackberry</strong></td>
<td valign="top">MP3, AAC</td>
</tr>
<tr>
<td valign="top"><strong>Mobile Safari (iPhone, iPad, iPod Touch)</strong></td>
<td valign="top">MP3, AAC</td>
</tr>
<tr>
<td valign="top"><strong>Opera Mobile</strong></td>
<td valign="top">Depending on the Device</td>
</tr>
</tbody>
</table>
<p style="text-align: left;">As you can see there is no single codec and format that is supported by all browsers and devices. In addition to this not every device does support the <strong><a href="http://caniuse.com/#feat=audio-api">WebAudio-API</a></strong> and some devices only allow audio-playback upon a user-interaction or only allow playing one sound at a time. So what should you do? Setup an audio file for any codec and then check the browser’s support before loading and playing the file? While this would be currently the only way to do it right, this not only sounds like a lot of work, but also is. What about browsers that don’t support the audio-element at all? – Implementing a flash fallback is no easy task as well.</p>
<hr />
<p><span style="color: #000000; font-weight: bold;">SoundJS</span></p>
<p style="text-align: left;">One possible solution is <strong><a href="http://www.createjs.com/#!/SoundJS">SoundJS</a></strong> – SoundJS is a JavaScript framework that will take care of all the compatibility issues with audio on different devices and even adds the ability of a flash-fallback should the browser support no audio. You would still have to provide different files for each sound to ensure that a soundfile is available for each device depending on the codec support but besides this, playing a sound with SoundJS can be done with 2 lines of JavaScript:</p>
<p></p><pre class="crayon-plain-tag">var src = ‘mySound.m4a|mySound.ogg’;
createjs.Sound.registerSound(src);
//…after the sound was loaded, it can be played by:
createjs.Sound.play(src);</pre><p></p>
<p style="text-align: left;">What I also like about SoundJS is that it features a plugin-system, so you can write your custom playback-plugin for individual needs, for example I used it to write a CocoonJS-plugin for it.</p>
<hr />
<p><span style="color: #000000; font-weight: bold;">howler.js</span></p>
<p style="text-align: left;">Another solution is <strong><a href="https://github.com/goldfire/howler.js/">howler.js</a></strong>, it is also released under the MIT license, so you can use it free in any of you projects it works very similar to SoundJS. One advantage over SoundJS is that it is very lightweight with only 9kb and offers pretty much the same functionality as SoundJS – with one exception though: howler.js features no flash-fallback, but if you are targeting mobile platforms, this should be no problem.</p>
<p></p><pre class="crayon-plain-tag">var sound = new Howl({
  urls: ['mySound.m4a','mySound.ogg']
}).play();</pre><p>Another thing I like about howler is the support of sound-sprites:</p><pre class="crayon-plain-tag">var sound = new Howl({
  urls: ['sounds.mp3', 'sounds.ogg'],
  sprite: {
    blast: [0, 1000],
    laser: [2000, 3000],
    winner: [4000, 7500]
  }
});

// shoot the laser!
sound.play('laser');</pre><p>&nbsp;</p>
<hr />
<p style="text-align: left;"><span style="color: #000000; font-weight: bold;">SoundManager 2</span><br />
A third option is <strong><a href="http://www.schillmania.com/projects/soundmanager2/">SoundManager 2</a></strong>, (<strong><a href="https://github.com/scottschiller/soundmanager2/">github</a></strong>), just like SoundJS it features a flash fallback if HTML5 audio is not supported. SoundManager2 is used by popular site like SoundCloud, last.fm or the Nyan Cat site. The focus of SoundManager2 is more on implementing audio-players on web-sites as it also features UIs for audio playback. Sounds are played like this:</p>
<p></p><pre class="crayon-plain-tag">// create "mySound"...
soundManager.createSound({
  id: 'mySound',
  url: '/path/to/an.mp3'
});

// ...and play it
soundManager.play('mySound');</pre><p>&nbsp;</p>
<hr />
<p><span style="color: #000000; font-weight: bold;">Comparison</span></p>
<p style="text-align: left;">As you can see, all three frameworks have their pros and cons, you should check out their sites and see what features you need for your project. The following table is just a very brief overview on the differences:</p>
<table style="font-size: 70%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="160"><strong>Feature/Player</strong></td>
<td width="160">
<p align="center"><strong>SoundJS</strong></p>
</td>
<td width="160">
<p align="center"><strong>howler.js</strong></p>
</td>
<td width="160">
<p align="center"><strong>SoundManager 2</strong></p>
</td>
</tr>
<tr>
<td width="160"><strong>Automatic playback of the correct codec/format</strong></td>
<td width="160">
<p align="center">Yes</p>
</td>
<td width="160">
<p align="center">Yes</p>
</td>
<td width="160">
<p align="center">Yes</p>
</td>
</tr>
<tr>
<td width="160"><strong>Flash fallback</strong></td>
<td width="160">
<p align="center">Yes</p>
</td>
<td width="160">
<p align="center">no</p>
</td>
<td width="160">
<p align="center">Yes</p>
</td>
</tr>
<tr>
<td width="160"><strong>Size (no gzip)</strong></td>
<td width="160">
<p align="center">25kb</p>
</td>
<td width="160">
<p align="center">9kb</p>
</td>
<td width="160">
<p align="center">34kb</p>
</td>
</tr>
<tr>
<td width="160"><strong>Sound Sprites</strong></td>
<td width="160">
<p align="center">No (can play with offset)</p>
</td>
<td width="160">
<p align="center">Yes</p>
</td>
<td width="160">
<p align="center">No (can play and stop at offset)</p>
</td>
</tr>
<tr>
<td width="160"><strong>License</strong></td>
<td width="160">
<p align="center">MIT</p>
</td>
<td width="160">
<p align="center">MIT</p>
</td>
<td width="160">
<p align="center">BSD</p>
</td>
</tr>
<tr>
<td width="160"><strong>Best used for*</strong></td>
<td width="160">
<p align="center">All-rounder, probably best used in combination with the CreateJS suite</p>
</td>
<td width="160">
<p align="center">games/mobile apps</p>
</td>
<td width="160">
<p align="center">Websites, mobile sites as an audio player</p>
</td>
</tr>
</tbody>
</table>
<p>*this doesn’t mean that you cannot use it for other cases, it’s just my personal evaluation</p>
<hr />
<p><span style="color: #000000; font-weight: bold;">A last word: Beware of MP3!</span></p>
<p style="text-align: left;">What a lot of people probably don’t know: <span style="text-decoration: underline;"><strong>MP3 is not free!</strong></span><br />
Implementing mp3 into your app/game is no problem, but what you should know is that if your game is ‘distributed’ (technically that includes 1 user playing the game in his browser) more than 5000 times, you have to pay an <a href="http://www.mp3licensing.com/royalty/games.html"><strong>mp3 codec royalty of $2500</strong></a>. But not only because of the licensing I would suggest you to use Ogg Vorbis(.ogg) or AAC(.m4a, MP4), OGG and AAC do have a better sound-quality while encoded with a smaller file-size than their MP3-counterpart.</p>
<p style="text-align: left;">If you want to learn more about the workflow of implementing audio into your html5- (mobile-) app/game and additional information on creating and publishing an HTML5 game, you should checkout my book at: <a href="http://indiegamr.com/zerotoappstore/">http://indiegamr.com/zerotoappstore/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/the-state-of-audio-in-html5-games/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8220;Can you make that loading screen stay longer?&#8221;</title>
		<link>http://indiegamr.com/can-you-make-that-loading-screen-stay-longer/</link>
		<comments>http://indiegamr.com/can-you-make-that-loading-screen-stay-longer/#comments</comments>
		<pubDate>Sun, 06 Jan 2013 04:58:42 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[tech]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=569</guid>
		<description><![CDATA[Or in other words: When everything that can be wrong with a client is wrong! &#8211; The client had already made a couple requests that seemed odd or made no sense in my eyes, but this one really sums up &#8230; <a href="http://indiegamr.com/can-you-make-that-loading-screen-stay-longer/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Or in other words: <strong>When everything that can be wrong with a client is wrong!</strong> &#8211; The client had already made a couple requests that seemed odd or made no sense in my eyes, but this one really sums up the nature of this client in one word.<br />
I&#8217;m currently working on a Phonegap App and the client&#8217;s latest request was to add a loading-screen to the app(not for initial loading), so we added a loading-screen.<br />
We didn&#8217;t think that one was necessary, but okay&#8230;the client wants a loading screen, so he gets one. Don&#8217;t get me wrong here, it&#8217;s not a splash-screen, it&#8217;s really just a loading-screen: <strong>a white screen, that says &#8220;loading&#8230;&#8221;</strong><br />
But it didn&#8217;t stop there: When he saw the thing implemented his reaction was like: &#8220;It dislays for less than a second, that makes the loading-screen seem kind of pointless. Can you make it stay longer?&#8221;</p>
<p>Long story short: This is probably the most senseless piece of code I have ever written and most likely will ever have written:</p><pre class="crayon-plain-tag">onComplete = function(e) {
  //...doing some other stuff

  // at this point everything is
  // loaded and ready to go
  // ...but ... you know ... the client ...
  setTimeout(
    function() {
      $('#loadingCover').hide();
    }, 3000
  );
}</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/can-you-make-that-loading-screen-stay-longer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>iOS html5 performance issues #2: scrollpanes and hardware acceleration</title>
		<link>http://indiegamr.com/ios-html5-performance-issues-with-overflow-scrolling-touch-and-hardware-acceleration/</link>
		<comments>http://indiegamr.com/ios-html5-performance-issues-with-overflow-scrolling-touch-and-hardware-acceleration/#comments</comments>
		<pubDate>Tue, 13 Nov 2012 06:41:22 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=509</guid>
		<description><![CDATA[Don&#8217;t try to force hardware acceleration on elements that are placed on a touch-scroll-pane! &#8230;and here&#8217;s why: I personally love the  &#8216;-webkit-overflow-scrolling: touch&#8217;-feature as it allows you to implement a scroll pane for mobile devices with just writing two lines of &#8230; <a href="http://indiegamr.com/ios-html5-performance-issues-with-overflow-scrolling-touch-and-hardware-acceleration/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><strong>Don&#8217;t try to force hardware acceleration on elements that are placed on a touch-scroll-pane!</strong> &#8230;and here&#8217;s why:</p>
<p>I personally love the  &#8216;-webkit-overflow-scrolling: touch&#8217;-feature as it allows you to implement a scroll pane for mobile devices with just writing two lines of css and no need of hasseling around with JS to make some content scroll smooth ect., however this approach also comes with a drawback: hardware acceleration will cause performance-issues on iOS (maybe other mobile devices, though it was only tested on an iPad2 running iOS6)</p>
<p>In my last post I was writing about forcing html5 hardware acceleration on iOS6, turns out you do NOT want to do that on every element as this can also cause the performance to drop, pointed out by the following example:<br />
<span id="more-509"></span><br />
The scenario is the following: The base is a big scrollpane using &#8216;<span style="font-family: 'Courier 10 Pitch', Courier, monospace !important;">-webkit-overflow-scrolling: touch</span>&#8216; that contains many images that are scaled from 100px width to 50px width.<br />
When combining this with forced hardware acceleration it will cause a massive drop in fps while scrolling.</p>
<p>Try it yourself by pointing your mobile browser to the following urls:<br />
<strong>Images Example</strong> <a href="http://labs.indiegamr.com/touch_scroll_performance/plain_images_nonaccel.html" target="_blank">Version 1: http://goo.gl/XIn9e</a> &#8211; NOT hardware accelerated, very good framerate<br />
<strong>Images Example</strong> <a href="http://labs.indiegamr.com/touch_scroll_performance/plain_images_accel.html" target="_blank">Version 2: http://goo.gl/DKC1u  </a>- hardware accelerated, low framerate while scrolling, however seems not to affect the execution of JS as the displayed fps does not drop</p>
<p>The only difference between Version 1 and Version 2 is:</p><pre class="crayon-plain-tag">img {
 -webkit-transform: translateZ(0);
 -webkit-perspective: 1000;
 -webkit-backface-visibility: hidden;
}</pre><p>The examples with HTMLImages shows a very huge drop in performance, however this effect is not solely limited to images but also &lt;div&gt; and other elements, even though it takes a larger number of divs to bring down the performance this way, it is possible:</p>
<p><strong>Divs Example</strong> <a href="http://labs.indiegamr.com/touch_scroll_performance/divs_nonaccel.html">Version 1: http://goo.gl/1iF71</a> &#8211; NOT accelerated, fluid, high fps<br />
<strong>Divs Example</strong> <a href="http://labs.indiegamr.com/touch_scroll_performance/divs_accel.html">Version 2: http://goo.gl/qkdwm</a> &#8211; accelerated, less frames on scrolling, seems to affect the execution speed of JS code</p>
<p>So bottom line: Forced hardware acceleration and <span style="font-family: 'Courier 10 Pitch', Courier, monospace !important;">&#8216;-webkit-overflow-scrolling: touch;&#8217;</span> do not work together very well!</p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/ios-html5-performance-issues-with-overflow-scrolling-touch-and-hardware-acceleration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iOS6 html hardware acceleration changes and how to fix them</title>
		<link>http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/</link>
		<comments>http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/#comments</comments>
		<pubDate>Sun, 30 Sep 2012 13:42:05 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=485</guid>
		<description><![CDATA[As probably many developers have already experience this over the past weeks: I had a phonegap application for iOS that contained some visually animated components  (a coverflow or a carousel for example). But after updating to iOS6 this is all &#8230; <a href="http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>As probably many developers have already experience this over the past weeks:<br />
I had a phonegap application for iOS that contained some visually animated components  (a coverflow or a carousel for example). But after updating to iOS6 this is all flickring now and it feels horrible because it&#8217;s just stumbling and faltering on the new version of the OS.<br />
There are several reasons for this and I cannot say which were already there in iOS5, however here are the two main reasons and instructions on how to fix that:<span id="more-485"></span></p>
<h2>1. Not all CSS Properties trigger hardware acceleration any more</h2>
<p>Previously there were quite a few properties that triggered a hardware acceleration, for example:</p>
<ul>
<li>-webik-transform: translate3d(x,y,z);</li>
<li>-webkit-transform: preserve-3d;</li>
<li>&#8230;</li>
</ul>
<p>As Apple states in its <a href="http://developer.apple.com/library/ios/#releasenotes/General/RN-iOSSDK-6_0/_index.html#//apple_ref/doc/uid/TP40012166-CH1-SW19" target="_blank">Developer Changelog for iOS6</a>: &#8216;<em>WebKit no longer always creates hardware-accelerated layers for elements with the <code>-webkit-transform: preserve-3d</code> option.[&#8230;]</em>&#8216; There is a need for new CSS properties to trigger the acceleration, unfortunately I&#8217;m not aware of any official document by Apple listing those properties.</p>
<p><strong>How to fix it:</strong><br />
Here are three properties that have been proven to work (at least in combination, I have not yet tested them solo, but they should):</p>
<ul>
<li>-webkit-transform: translateZ(0);</li>
<li>-webkit-perspective: 1000;</li>
<li>-webkit-backface-visibility: hidden;<a href="http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/ios6-performance-overlapping/" rel="attachment wp-att-489"><br />
</a></li>
</ul>
<p>As this is going to trigger hardware acceleration for the specified elements this might still not completely fix all the issues, therefore please continue reading Nr.2.</p>
<hr />
<h2>2. Overlapping with other Elements</h2>
<p>Since I cannot downgrade to iOS5 I cannot say for sure if this &#8220;issue&#8221; already persisted, however it heavily persists with iOS6:<br />
<a style="font-style: normal; line-height: 24px; text-decoration: underline;" href="http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/ios6-performance-overlapping/" rel="attachment wp-att-489"><br />
</a>If you have an element(Element A) that is hardware accelerated and animated, it will/might cause performance and visual issues when overlapping with other elements(Element B) that are not hardware accelerated, as Element A will trigger Element B to be re-rendered with every change of Element A(at the end of a CSS-transition or when updating CSS properties through JS), which will cause:</p>
<ul>
<li><strong>flickering of Element B, since it renders a lot slower</strong></li>
<li><strong>heavy slowdown of the animation, since it needs more CPU time to render leaving less time for JS execution</strong></li>
</ul>
<p>One thing I noticed: If Element A OVERlaps another element it is not slowing down the animation as heavy as if Element A was UNDERlapping another element. Also it does not really matter if the parent-container of Element A has &#8216;overflow: hidden;&#8217; or &#8216;overflow: visible;&#8217; &#8211; it still slows doen the execution if the overlapping occures outside the bounds of the parent container.</p>
<p><strong>How to fix it:<br />
</strong> a) This can be simply fixed by giving ALL overlapping elements the CSS properties that trigger hardware accerleration. (<strong>see 1.</strong>)<br />
(My first approach to fix this was by alternating the DOM-order to only have OVERlapping elements, however fix a) is way easier and works way better &#8211; for me.)</p>
<p>I have visualized this here:<a href="http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/ios6-performance-overlapping/" rel="attachment wp-att-489"><img class="aligncenter size-full wp-image-489" title="ios6-performance-overlapping" src="http://indiegamr.com/wp-content/uploads/ios6-performance-overlapping.png" alt="" width="768" height="400" /></a></p>
<p>&nbsp;</p>
<p>edit1: 16-10-2012</p>
<hr />
<h2>3. Avoid changes between &#8216;display: none;&#8217; and &#8216;display: something;&#8217;</h2>
<p>Changing the display-state on iOS is like adding or removing an element to and from the DOM and is therefor a very heady calculation depending on how many items you have in your DOM that can easyly cause the UI to freeze for a second or more.</p>
<p><strong>How to fix it:</strong><br />
Instead of using the display-property, use the tranform-property instead, if you want to hide an item you can use something like this: transform:</p><pre class="crayon-plain-tag">translate(100000px,100000px);</pre><p>and if you want to show the element, just set the values to 0:</p><pre class="crayon-plain-tag">translate(0px,0px);</pre><p>You have to set the &#8216;position: absolute;&#8217; though. This method needs a little bit more work than using &#8216;display&#8217;, however the performance of your webapp will thank you greatly for that.</p>
<p>&nbsp;</p>
<p>I hope this helps someone as I was struggeling with this issue for quite a while, thoughts or additions on this article are very welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>Coming up with new App ideas</title>
		<link>http://indiegamr.com/coming-up-with-new-app-ideas/</link>
		<comments>http://indiegamr.com/coming-up-with-new-app-ideas/#comments</comments>
		<pubDate>Thu, 13 Sep 2012 19:07:50 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=462</guid>
		<description><![CDATA[Here are some thoughts on the current App &#8216;situation&#8217; and how the next generation of apps might or could look like by taking ideas from old/bad apps: (NOTE: In this article I am NOT talking about Games or Gaming Apps, &#8230; <a href="http://indiegamr.com/coming-up-with-new-app-ideas/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here are some thoughts on the current App &#8216;situation&#8217; and how the next generation of apps might or could look like by taking ideas from old/bad apps:<br />
<span style="font-size: 12px;">(NOTE: In this article I am NOT talking about Games or Gaming Apps, for those it looks kind of different)</span></p>
<p>Let&#8217;s face it: &#8220;There is an app for everything!&#8221; &#8211; However looking at the two major App Stores, iTunes and Play, there are serveral types of apps.<br />
Now the division of those apps are not backed by any statistics and are only based on my perception of the appstores and my experience browsing through the stores:</p>
<table style="font-size: 14px !important;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="64"> Type</td>
<td width="406">Description</td>
<td width="57">Percentage</td>
</tr>
<tr style="background-color: #9f6;">
<td width="64"><strong>  A Apps</strong></td>
<td width="406">Quality/Polished Apps, developed by backed/bigger companies</td>
<td width="57"><strong>20%</strong></td>
</tr>
<tr style="background-color: #69f;">
<td width="64"><strong>  B Apps</strong></td>
<td width="406">Niche Apps by &#8216;small&#8217; developers/indie devs that do generate some revenue</td>
<td width="57"><strong>15%</strong></td>
</tr>
<tr style="background-color: #ff9;">
<td width="64">  <strong>C Apps</strong></td>
<td width="406">Innovative/Useful Apps that are either unknown or badly executed</td>
<td width="57"><strong>20%</strong></td>
</tr>
<tr style="background-color: #aaa;">
<td width="64"><strong>  D Apps</strong></td>
<td width="406">&#8216;Crappy&#8217; Apps that are either badly executed, a bad copy of another A-App or have just no real use whatsoever</td>
<td width="57"><strong>45%</strong></td>
</tr>
</tbody>
</table>
<p><span id="more-462"></span><br />
Now, what I want to take from this:<br />
Making an A-App as an indie dev is very unlikely. D-Apps are not worth looking into, since they are all bad and/or copied. What I want to look at is B and C. I used to browse through the App Store looking at Apps and sometimes found a neat, innovatice App or cool idea &#8211; however I always say to myself things like &#8216;<em>Too bad it already exists, I could have made an app like that</em>&#8216; or &#8216;<em>Well someone tried it, but looks like noone&#8217;s downloading it, so noone wants an app like that</em>&#8216; &#8211; Well, while this might apply to some apps, it won&#8217;t apply to the majority of those apps. In my opinion the majority of those C-Apps have no success because of their UI and their usability. Think about it: Would you really use an app with a badly designed UI that&#8217;s not fun to use at all, even if it could be of use for you? Probably Not.<br />
And that&#8217;s why C-Apps are interesting for any indie dev! They are innovative and usually of good use for their customers, however their execution is bad. So the key of succeeding could be an idea of an existing app but without its flaws and with an awesome, kickass UI. I personally, truly believe that there is potential in those apps. There doesn&#8217;t allways have to be something completely new to succeed, it can just as well be an old idea picked up and executed well.</p>
<p style="text-align: center;"><strong><span style="color: #333333;">&#8220;Taking an idea&#8221; does not equal &#8220;rip off&#8221;</span></strong></p>
<p>I&#8217;m not saying that you should go ahead and rip off other indie developers by copying an app 1to1, it is more like taking an idea and shaping a new, better product out of it and maybe even form new ideas during that process. In my eyes this is where innovation comes from.</p>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/coming-up-with-new-app-ideas/feed/</wfw:commentRss>
		<slash:comments>2</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 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>
		<item>
		<title>Retro Style Platform Runner Game for mobile with EaselJS (Part 1)</title>
		<link>http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/</link>
		<comments>http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/#comments</comments>
		<pubDate>Sun, 01 Jul 2012 13:55:43 +0000</pubDate>
		<dc:creator><![CDATA[olsn]]></dc:creator>
				<category><![CDATA[EaselJS]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://indiegamr.com/?p=113</guid>
		<description><![CDATA[Editors Note: The tutorial is a little bit outdated now, but it still works. However if you would like to learn more on this topic and get a more detailed verison plus all the extras and resources, you should check &#8230; <a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><em>Editors Note: The tutorial is a little bit outdated now, but it still works. However if you would like to learn more on this topic and get a more detailed verison plus all the extras and resources, you should check out my ebook: <a href="http://indiegamr.com/zerotoappstore/">From Zero to the Appstore &#8211; Blueprints for an HTML5 Game</a>.</em></p>
<p>Here I&#8217;m starting a series of 4 articles on how to create a small game with <a href="http://createjs.com/#!/EaselJS" target="_blank">EaselJS </a>that &#8220;can&#8221; run on your mobile device (<strong>unfortunately it won&#8217;t run on all mobile devices</strong>) &#8211; however I also plan on a future posting on how to use technologies like <a href="http://www.ludei.com/tech" target="_blank">cocoonJS</a> to create a WELL-PERFORMING native app from this.</p>
<h2>The FINAL result</h2>
<hr />
<p>The result is going to look similar to this (but with better code!) &#8211; In case you take a look at the source-code: This is NOT a good example on how to code cleanly &#8211; I did this as a quick mashup to try out a few things. &#8211; <strong>You can also do another jump, while in the air:</strong></p>
<p><iframe width="100%" height="240" src="http://demos.indiegamr.com/jumpy"></iframe></p>
<p>To test this on your mobile device, point your mobile browser to: <a href="http://demos.indiegamr.com/jumpy" target="_blank">http://demos.indiegamr.com/jumpy</a><span id="more-113"></span></p>
<h2>The result of Part 1&amp;<a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/" target="_blank">Part 2</a></h2>
<hr />
<p><iframe width="100%" height="380" src="http://demos.indiegamr.com/jumpy/part1/"></iframe></p>
<h2>Let&#8217;s get started with the basics &#8211; Setting up the Stage</h2>
<hr />
<p>Working with EaselJS is pretty simple, especially when you worked with ActionScript3 before, as a lot of the methods and classes are based on ActionScript3-equivalents. So basically the first thing you have to do in order to see a result, is to create a canvas-element and set up the &#8220;<a href="http://createjs.com/Docs/EaselJS/Stage.html" target="_blank">Stage</a>&#8221; here is how this can be done:</p><pre class="crayon-plain-tag">// creating the canvas-element
canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 250;
document.body.appendChild(canvas);

// initializing the stage
stage = new Stage(canvas);</pre><p>However, if you tried this out, it wouldn&#8217;t bring you that much of a result, because in order to actually see something the Stage has to be &#8216;updated&#8217; (stage.update();) by EaselJS, also this is something, that has to be done every frame &#8211; so to do that, we can setup an event, that will update the Stage every frame.</p><pre class="crayon-plain-tag">Ticker.setFPS(30);
Ticker.addListener(tick);
function tick(e) {
	stage.update();
}</pre><p>Great! Now we have a stage, that is updated with 30 frames/second.</p>
<h2>More basics &#8211; Adding something to the stage</h2>
<hr />
<p>Now that we&#8217;ve setup the Stage, we can obviously still see nothing, because there is no object/image there to display.</p>
<p>The basic flow of doing this is to: 1) Preload an Image then 2) Create an DisplayObject with that image and finally 3) add this DisplayObject to the Stage(or another Container)</p><pre class="crayon-plain-tag">var img = new Image();
img.onload = onImageLoaded;
img.src = 'asset/myImage.png';

function onImageLoaded(e) {
	var myBitmap = new Bitmap(img);
	stage.addChild(myBitmap);
}</pre><p><strong>Preloading:</strong><br />
Some might ask here, why I&#8217;m not introducing <a href="http://createjs.com/#!/PreloadJS" target="_blank">PreloadJS</a> to preload all the assets (or in this case: one asset) &#8211; well PreloadJS is a very nice way to do so &#8211; and I also recommend using it for some projects, but I tried running the app with the <a href="http://www.ludei.com/tech/cocoonjslauncher" target="_blank">cocoonJS-launcher</a> and receiveed a big load of Errors from cocoon(due to cocoon&#8217;s limited JS-parsing). Now this is NOT the fault of PreloadJS, however since preloading assets is nothing super-complicated, that requires super-extensive knowlege(basically one function), I chose to use an own 5-line implementation to achieve this.</p>
<h2>Great! &#8211; So how do I make a game from this?</h2>
<hr />
<p>Well, a typical game usually needs the following things:</p>
<ul>
<li>Part 1: User-Input (Keystrokes, MouseClick, Touch)  &amp; Movement</li>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/" target="_blank">Part 2: Collisions between objects</a></li>
<li>Part 3: Animations</li>
</ul>
<h2>User Input</h2>
<hr />
<p>To listen to userinput-events we first have to distinguish if the device is a touch-device or has a regular screen and add the according event listeners.</p><pre class="crayon-plain-tag">//check for a touch-option
if ('ontouchstart' in document.documentElement) {
	canvas.addEventListener('touchstart', function(e) {
		handleKeyDown();
	}, false);

	canvas.addEventListener('touchend', function(e) {
		handleKeyUp();
	}, false);
} else {
	document.onkeydown = handleKeyDown;
	document.onkeyup = handleKeyUp;
	document.onmousedown = handleKeyDown;
	document.onmouseup = handleKeyUp;
}

function handleKeyDown(e)
{
	// execute things on KeyDown
	// e.g.
	hero.jump();
}

function handleKeyUp(e)
{
	// execute things on KeyUp
}</pre><p>This is pretty straight forward and should widely explain itself.</p>
<h2>Movement</h2>
<hr />
<p>To create movement, the simples thing to do is e.g. to alter the position of an object a little bit every frame, just like this:</p><pre class="crayon-plain-tag">function tick(e) {
	//this will move the object down by 1 pixel
	myBitmap.y += 1;
	//this will update the stage
	stage.update();
}</pre><p>However in order to get the whole thing not too messy, once there are more objects involved in the scene, we should setup an own class for each object, or at least each object that is moving, as an example I put together the following:</p><pre class="crayon-plain-tag">(function (window) {
	function Hero(image) {
		this.initialize(image);
	}
 	Hero.prototype = new Bitmap();

 	// save the original initialize-method so it won't be gone after
 	// overwriting it
 	Hero.prototype.Bitmap_initialize = Hero.prototype.initialize;

 	// initialize the object
 	Hero.prototype.initialize = function (image) {
 		this.Bitmap_initialize(image);
 		this.name = 'Hero';
 		this.snapToPixel = true;
 	}

 	// we will call this function every frame to 
	Hero.prototype.tick = function () {
		this.y += 1;
 	}

 	// this will reset the position of the hero
 	// we can call this e.g. whenever a key is pressed
 	Hero.prototype.reset = function() {
 		this.y = 0;
 	}

 	window.Hero = Hero;
} (window));</pre><p>With the Hero-class implemented, we can now create a hero object and apply some interaction, all together it would look like this:</p><pre class="crayon-plain-tag">if ('ontouchstart' in document.documentElement) {
	canvas.addEventListener('touchstart', function(e) {
	handleKeyDown();
	}, false);
} else {
	document.onkeydown = handleKeyDown;
	document.onmousedown = handleKeyDown;
}

var	stage,
	canvas,
	hero,
	img = new Image();

function init() {
	canvas = document.createElement('canvas');
	canvas.width = getWidth();
	canvas.height = getHeight();
	document.body.appendChild(canvas);

	stage = new Stage(canvas);

	img.onload = onImageLoaded;
	img.src = 'assets/hero.png';
}

function onImageLoaded(e) {
	hero = new Hero(img);
	stage.addChild(hero);
	hero.reset();

	Ticker.setFPS(30);
	Ticker.addListener(tick);
}

// move the hero down by 1px
// and update/render the stage
function tick() {
	hero.tick();
	stage.update();
}

// whenever a key is pressed then hero's
// position will set to y=0;
function handleKeyDown(e)
{
	hero.reset();
}

init();</pre><p>here&#8217;s how it should look like(depending on the background-color, that you chose for your html-body):</p>
<p><iframe width="100%" height="200" src="http://demos.indiegamr.com/jumpy/part1/index_basic.html"></iframe></p>
<p>Of course this is very basic, and the movement is absolutely not realistic, since there is no acceleration in the movement, but we can fix this by adding a velocity-object to the hero, just add the following:</p><pre class="crayon-plain-tag">//add this to the &quot;initialize&quot;-method
this.velocity = {x:0,y:12};

//now we update the &quot;tick&quot;-method with:
this.velocity.y += 1;
this.y += this.velocity.y;

//and this goes into the &quot;reset&quot;-method:
//getHeight() is a utility-function, but can also be
//replaced with a hardcoded-number
this.y = getHeight() / 1.25;
this.velocity.y = -15;</pre><p>and this is how it should look like by now:</p>
<p><iframe width="100%" height="200" src="http://demos.indiegamr.com/jumpy/part1/index_basic2.html"></iframe></p>
<p>Awesome, now we have a basic &#8220;game&#8221;, with a character falling down, that will be reset on any user-input. The next parts are going to cover collisions and animations.</p>
<p>You can download the source-files here: <a href="http://demos.indiegamr.com/jumpy/part1/part1.zip" target="_blank">download</a></p>
<hr />
<p><strong>Agenda</strong></p>
<p>&nbsp;</p>
<ul>
<li><strong>Part 1: User-Input (Keystrokes, MouseClick, Touch)  &amp; Movement</strong></li>
<li><a href="http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-2/" target="_blank">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/" target="_blank">Part 3: Movement&amp;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 &amp; eye candy</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://indiegamr.com/retro-style-plattform-runner-game-for-mobile-with-easeljs-part-1/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
	</channel>
</rss>
