<?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>Userbag.co.uk</title>
	<atom:link href="http://userbag.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://userbag.co.uk</link>
	<description>The blog of Carl</description>
	<lastBuildDate>Sun, 18 Mar 2012 22:23:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PJAX-Standalone &#8211;  Pushstate Ajax</title>
		<link>http://userbag.co.uk/development/pjax-standalone-pushstate-ajax/</link>
		<comments>http://userbag.co.uk/development/pjax-standalone-pushstate-ajax/#comments</comments>
		<pubDate>Sat, 17 Mar 2012 20:44:10 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[pjax]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=386</guid>
		<description><![CDATA[PJAX or Pushstate AJAX is a fairly new twist on the traditional AJAX page loading idea, although unlike its predecessors PJAX takes advantage of the new Pushstate history API&#8217;s in order to provide it with real permalinks and history as opposed the the document.hash based hacks which the former has had to make do with. The result is that [...]]]></description>
			<content:encoded><![CDATA[<p>PJAX or Pushstate AJAX is a fairly new twist on the traditional AJAX page loading idea, although unlike its predecessors PJAX takes advantage of the new Pushstate history API&#8217;s in order to provide it with real permalinks and history as opposed the the document.hash based hacks which the former has had to make do with.</p>
<p>The result is that its now possible to gain the performance boosts that AJAX page loading makes possible, across the majority of the major browsers (IE not included), without any fear of compromising backwards compatibility or the native behaviours of the browser (back button etc).</p>
<p>Unfortunately the main source of PJAX goodness is JQuery plugin ( <a title="JQuery PJAX" href="https://github.com/defunkt/jquery-pjax">jquery-pjax</a>) meaning that those who favour alternative JavaScript frameworks &#8211; or even none at all &#8211; are left out in the cold.</p>
<p>To remedy this, I decided to create my own standalone implementation of PJAX (Which I insightfully named as <a title="PJAX Standalone. PJAX for none JQuery Users." href="https://github.com/thybag/PJAX-Standalone">PJAX-Standalone</a>). Like its counterpart PJAX-standalone was designed to be highly customisable while at the same time, incredibly easy to get working. For many webpages nothing more than the addition of an ID to your content container and a single call to the PJAX-Standalone script is required.</p>
<p>For those who want more functionality a number of callbacks can also be set in addition to being able to invoke PJAX page loading programmatically as well.</p>
<p>You can see an example of the script in action on the <a title="PJAX Standalone Demo Page." href="http://userbag.co.uk/demo/pjax/">PJAX-Standalone demo page</a>.</p>
<p>Full details on how to use and configure PJAX-Standalone can be found on  <a title="PJAX Standalone Github page" href="https://github.com/thybag/PJAX-Standalone">Github</a>.</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2012. |
<a href="http://userbag.co.uk/development/pjax-standalone-pushstate-ajax/">Permalink</a> |
<a href="http://userbag.co.uk/development/pjax-standalone-pushstate-ajax/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/development/pjax-standalone-pushstate-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ubuntu 11.10 &#8211; Setting up with LXDE</title>
		<link>http://userbag.co.uk/blogging/ubuntu-11-10-setting-up-with-lxde/</link>
		<comments>http://userbag.co.uk/blogging/ubuntu-11-10-setting-up-with-lxde/#comments</comments>
		<pubDate>Sun, 04 Mar 2012 13:42:34 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Blogging]]></category>
		<category><![CDATA[AWN]]></category>
		<category><![CDATA[cardapio]]></category>
		<category><![CDATA[desktop]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[LXDE]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[xcompmgr]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=366</guid>
		<description><![CDATA[I like Ubuntu, it&#8217;s not every ones favourite linux distribution, but for me, it&#8217;s always done what I&#8217;ve needed it to. Installation is simple and painless, and almost everything I want comes with it out of the box. Or at least it used to. Maybe I&#8217;m just falling into the &#8220;I hate change&#8221; trap, but Unity, for me at [...]]]></description>
			<content:encoded><![CDATA[<p>I like Ubuntu, it&#8217;s not every ones favourite linux distribution, but for me, it&#8217;s always done what I&#8217;ve needed it to. Installation is simple and painless, and almost everything I want comes with it out of the box. Or at least it used to.</p>
<p>Maybe I&#8217;m just falling into the &#8220;I hate change&#8221; trap, but Unity, for me at least, just isn&#8217;t what I&#8217;m after. Despite a number of attempts to get used it it,  it just  feels awkward to use and doesn&#8217;t really fit with the way I want to interact with my computer. Switching back to the gnome environment doesn&#8217;t really do the trick either, as I just find myself annoyed at how the gnome 3 &#8220;classic&#8221; mode has stripped out so many of the features I took for granted. Gnome 3 itself&#8230; lets not even go there. So there is the problem, as much as I like Ubuntu, it no longer provides me with an interface I&#8217;m comfortable with.</p>
<p>Rather than just continue to moan about all this stuff at great length, I decided I would actually spend a little time being semi-constructive and have a tinker with some of the other options out there (<a href="http://www.xfce.org/">XFCE</a>  and <a href="http://www.lxde.org/">LXDE</a> being the main contenders). Since I&#8217;ve used xfce in the past, I opted to give my attention to LXDE.</p>
<p>I already had a blank <a href="http://www.ubuntu.com/download/ubuntu/download">Ubunutu 11.10</a> installation sitting around in VirtualBox, so I decided to use that as my base, rather than downloading and installing the proper <a href="http://lubuntu.net/">lubuntu</a> installation.</p>
<p>To begin, I booted up virtual box and logged in to the Ubuntus default unity environment. Then to add the LXDE desktop, I opened up the terminal and ran:</p>
<pre class="brush: bash; gutter: true">sudo apt-get install lxde</pre>
<p>After agreeuing to its demands (50 or so mb of space) and waiting for it to complete, I logged out, switched my environment from &#8220;Unity&#8221; to &#8220;LXDE&#8221; (right click the cog next to the login box to select this) and logged back in.</p>
<p>I was then greeted by the following functional (although not especially pretty) desktop.</p>
<div id="attachment_369" class="wp-caption aligncenter" style="width: 310px"><a href="http://userbag.co.uk/wp-content/uploads/2012/03/start.png"><img class="size-medium wp-image-369 " title="LXDE Default Desktop" src="http://userbag.co.uk/wp-content/uploads/2012/03/start-300x245.png" alt="LXDE Default Desktop" width="300" height="245" /></a><p class="wp-caption-text">LXDE Default Desktop</p></div>
<p>Although not as fully featured as gnome, I was happy to find the interface provided pretty much everything I wanted (including the ability to freely customise the panels). The only real issues I found with the interface, was the clunky and cluttered menu, and its (in my opinion) somewhat unattractive looks. Thankfully, this being Linux, both issues were fairly straightforward to solve.</p>
<p>My first target was the start menu, having come from a windows system the thing I missed most in the menu was the ability to quickly search for what I was after. To solve this problem, I opted to use <a href="https://launchpad.net/cardapio">Cardapio</a> as it offered the above functionality in addition to being stand alone (making it easy to get running).</p>
<p>To get cardapio installed, you&#8217;ll want to run the following 3 commands in the terminal which will add the cardapio repository and then download cardapio itself (along with  tracker &#8211; in order to allow file searches, and python-glade2 which is a missing dependency of cardapio).</p>
<pre class="brush: bash; gutter: true">sudo add-apt-repository ppa:cardapio-team/unstable
sudo apt-get update
sudo apt-get install cardapio tracker python-glade2</pre>
<p>Once cardapio is installed, the next step is the slighly more difficult task of setting it up in place of the default start menu. Since I was unable to find any reliable documention on how to do this properly, I fiddled around and finally settled on the solution of &#8220;botching&#8221; it by replacing the panels &#8220;Menu&#8221; with an &#8220;Application launch bar&#8221; containing only the cardapio icon.</p>
<p>To do this right click the taskbar and select &#8220;Add / Remove panel items&#8221;. Then in the dialog, select &#8220;Add&#8221; and &#8220;Appliction launch bar&#8221;. This should place the new &#8220;appliction launch bar&#8221; on the end of the panel, use the up button to move it in front of the existing &#8220;Menu&#8221;. Double clicking this will now give you the opportunity to add applictions to the &#8220;launch bar&#8221;. Unfortunately, Cardapio is no where to be seen.</p>
<p>This is becuse cardapio by deafult is set to hidden. To fix this, in your terminal window run.</p>
<pre class="brush: bash; gutter: true">sudo nano /usr/share/applications/cardapio.desktop</pre>
<p>Then using nano, change the value of &#8220;NoDisplay&#8221; from true to false and save over the original file.</p>
<p>On opening your appliction launch bar again, you should now find Cardapio helpfully listed under &#8220;Accessories&#8221;. Hit add to move it in to the Launcher, then close the window and give it a try.</p>
<p>With a decent start manager now in place, the next step is just to pretty it up.</p>
<p>To start with I right click the task bar, selected &#8220;Panel Settings&#8221; and changed the panel Edge to &#8220;top&#8221; (to place the panel at the top of the desktop). Then in the &#8220;Appearance&#8221; tab, I change from &#8220;Image&#8221; to solid &#8220;color (with optacity)&#8221; and adjusted the colour and opacity in order to provide a semi-transparent black taskbar.</p>
<p>Next, install avant-window-navigator (my dock of choice) using:</p>
<pre class="brush: bash; gutter: true">sudo apt-get install avant-window-navigator</pre>
<p>Once installed, open the start menu and select AWN (just search avant) which should start it running. Don&#8217;t worry that it looks hidious at this point. Just right click the dock and select dock preferences, then in the main panel tick the box that says &#8220;start Awn automatically&#8221; and close it.</p>
<p>To make AWN (Avant Window Navigator) display correctly, you will now need to install and enable a &#8220;compositor&#8221;. I opted to use &#8220;xcompmgr&#8221; for this purpose. Install it using:</p>
<pre class="brush: bash; gutter: true">sudo apt-get install xcompmgr</pre>
<p>And to ensure it starts up whenever your copy of ubuntu does, You&#8217;ll need to create it a new startup entry.</p>
<p>Run:</p>
<pre class="brush: bash; gutter: true">sudo nano /etc/xdg/autostart/XCompmgr.desktop</pre>
<p>And add the following data:</p>
<pre class="brush: text; gutter: true">[Desktop Entry]
Encoding=UTF-8
Name=XCompmgr
Type=Application
Comment=XCompmgr--a light compositor
Exec=xcompmgr
Terminal=false
OnlyShowIn=LXDE</pre>
<p>Once this is done, save, then  logout and in again to see the effects.</p>
<p>Now you have a dock, there is not much point having your running applictions listed up top, so right click the panel, select &#8220;add/remove items&#8221; and remove the &#8220;Task bar&#8221; and any other unwanted bits from it.</p>
<p>You can also right click AWN and select a more fitting theme within dock preferences.</p>
<p>To finish off prettying up the desktop, I&#8217;d suggest changing the desktop background by right clicking the desktop, selecting preferences and then setting it to use an image of your choice. Adjusting the Theme can then be done using lxAppearence (I stuck with clearlook but switched the highlight colour from orange to dark grey) and Configure the window chrome using the &#8220;openbox configution manager&#8221;. I switched the theme from &#8220;Onyx&#8221; to &#8220;Carbon&#8221;.</p>
<p>The end result, with a little luck should now be a somewhat prettier looking LXDE, with a decent start menu and a nice dock. What&#8217;s more, even with all the extra stuff, It&#8217;s still quite noticeably nippier than both Unity and Gnome.</p>
<div id="attachment_372" class="wp-caption aligncenter" style="width: 310px"><a href="http://userbag.co.uk/wp-content/uploads/2012/03/end.png"><img class="size-medium wp-image-372" title="LXDE Tweaked" src="http://userbag.co.uk/wp-content/uploads/2012/03/end-300x244.png" alt="LXDE Tweaked" width="300" height="244" /></a><p class="wp-caption-text">LXDE Tweaked</p></div>
<p>As one final task for those using the AutoLogin feature in Ubuntu, you will need to set Ubuntu to use LXDE by default. You can do this with the following command:</p>
<pre class="brush: bash; gutter: true">sudo /usr/lib/lightdm/lightdm-set-defaults -s LXDE</pre>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2012. |
<a href="http://userbag.co.uk/blogging/ubuntu-11-10-setting-up-with-lxde/">Permalink</a> |
<a href="http://userbag.co.uk/blogging/ubuntu-11-10-setting-up-with-lxde/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/blogging/ubuntu-11-10-setting-up-with-lxde/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making HTML5 games by someone who knows nothing about making games: Part 2</title>
		<link>http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games-part-2/</link>
		<comments>http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games-part-2/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 22:49:28 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[HTML5 Games]]></category>
		<category><![CDATA[browser based]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[game making]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sprite.js]]></category>
		<category><![CDATA[tank]]></category>
		<category><![CDATA[tank combat]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=316</guid>
		<description><![CDATA[Hello, welcome to the (somewhat overdue) second part of my &#8220;Making HTML5 games by someone who knows pretty much nothing about making games&#8221; series. If you&#8217;ve not read the first part ( see here ) then it&#8217;s probably a good idea to check that out first as the plan is to try and continue from [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_348" class="wp-caption alignright" style="width: 279px"><img class="size-full wp-image-348" title="tank_tumb" src="http://userbag.co.uk/wp-content/uploads/2012/02/tank_tumb1.png" alt="Tank combat Screenshot" width="269" height="236" /><p class="wp-caption-text">Tank Combat</p></div>
<p>Hello, welcome to the (somewhat overdue) second part of my &#8220;Making HTML5 games by someone who knows pretty much nothing about making games&#8221; series. If you&#8217;ve not read the first part ( <a href="http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games/">see here</a> ) then it&#8217;s probably a good idea to check that out first as the plan is to try and continue from where I left off. If you want to jump right in you can grab a copy of the code produced previously <a href="http://userbag.co.uk/demo/g1_demo/g_3/">here</a>.</p>
<p>So, just as a recap, the &#8220;game&#8221; if it can be called that at this stage is being build using the <a href="https://github.com/batiste/sprite.js/">Sprite.js</a> framework and currently consists of a black screen and an ugly looking triangle, which can be controlled using both the arrow and wasd keys. In order to try and bring the &#8220;game&#8221; closer to something worthy of that description, the next logical step is to start adding a few more features to our game. Shooting, bad guys, stuff like that.</p>
<p>To do this, its probably a good idea to figure out exactly what kind of game we are planning to make, and thus which features its going to need. In the previous tutorial, I&#8217;d kinda been thinking of creating a space style shooter, although, to be honest, I don&#8217;t really think the movement method fits to well with that. Additionally, I feel like trying something a bit different.</p>
<p>So what&#8217;s the new plan?</p>
<h2>Tank Combat</h2>
<p>Use a tank to fight off the evil alien invaders.</p>
<p>The main aim of this tutorial is to create the above game, with the following four key features;</p>
<ul>
<li>The ability to drive the tank with the arrow and wasd keys.</li>
<li>The ability to aim and shoot using the mouse.</li>
<li>To have some sort of enemy to fight.</li>
<li>To have some graphics that actually fit the new game idea.</li>
</ul>
<p>Given this, I think the first step is to start bringing our existing &#8220;game&#8221; into line with the new vision.<br />
To start, I&#8217;ve created a new &#8220;tank&#8221; sprite (just a really basic pixel tank).</p>
<div class="centre_zone"><img src="http://userbag.co.uk/demo/g1_demo/g_7/tank.png" alt="Tank Sprite" /></div>
<p>The tank sprite consist&#8217;s of three panels. The first two display the tank body at different stages of movement (basically the tracks move slightly) and the third shows the tanks gun turret, which needs to be separate from the hull so we can position and rotate it separately.</p>
<p>To add the sprite into the game, we will need to update our &#8220;ship&#8221; sprite definition. I will also rename &#8220;ship&#8221; to &#8220;tank&#8221; while here, just to avoid confusion (remember in addition to changing the sprite file, its also important to update the sprite definition with the new sprites width and height).</p>
<pre class="brush: javascript; gutter: true">tank = this.mytank = this.scene.Sprite("tank.png",{
	"layer": this.layer, //Layer tanks will be displayed in.
	"x": 100, 	//X position of sprite
	"y": 100, 	//Y position of sprite
	"w": 36, 	//width of sprite.
	"h": 59 	//height of sprite.
});</pre>
<p>To go with the new sprite, you may also want to change the game&#8217;s background colour from black to green (like grass) so it fits a little better with the new theme.</p>
<p>Although the tank sprite is now in the game, it&#8217;s movement still feels a little wrong, since it was originally set up on the premise that we were going to be controlling a space ship. Because of this I think its worth spending a little time tweaking the way our sprite moves. To start friction plays a much bigger role when not in space, so to replicate this I&#8217;ve added an else, to slow the tank down when not accelerating and, in addition I also lowered the acceleration speed from 0.5 to +0.2.</p>
<pre class="brush: javascript; gutter: true">if(this.inputs.keyboard.up){
	if(speed&lt;5) speed = speed+0.2;
}else{
	//Apply friction
	if(speed&gt;0) speed = speed-0.1;
}</pre>
<p>While we are playing with movement, it&#8217;s also a good time to add some code to stop the tank from constantly flying of the screen as you drive around. To do this, in its simplest form, we just need to add some code that will check whether or not the x &amp; y coordinates the tank is moving too are within the current scene (on screen) and if not, stop that movement from being applied.</p>
<p>To do this add something along the lines of this just above where the new tank position and angle are applied to the sprite (above the comment &#8220;//Tell the tank&#8221;).</p>
<pre class="brush: javascript; gutter: true">	//Ensure new X position is inside playable area
	if(nx &lt; 0 || (nx + this.mytank.w) &gt; this.layer.w){
		nx = this.mytank.x;
	}
	//Ensure new Y position is inside playable area
	if(ny &lt; 0 || (ny + this.mytank.h) &gt; this.layer.h){
		ny = this.mytank.y;
	}</pre>
<p>With a little luck you should find that you are no longer able to drive your tank outside of the game area. While this gets the job done, it (for me at least) feels a little clunky. My solution to this was simply to swap the outright stop effect for a simple bounce effect instead. The new code looks as follows:</p>
<pre class="brush: javascript; gutter: true">	//Ensure new X position is inside playable area
	if(nx &lt; 0 || (nx + this.mytank.w) &gt; this.layer.w){
		speed = -(speed*0.4);
		nx = this.mytank.x;
	}
	//Ensure new Y position is inside playable area
	if(ny &lt; 0 || (ny + this.mytank.h) &gt; this.layer.h){
		speed = -(speed*0.4);
		ny = this.mytank.y;
	}</pre>
<p>It works in a very similar way to the simple stop, except rather than simply stopping the ship it also reverses the ship&#8217;s momentum at the same time.</p>
<p>Now that it is possible for the tank to have negative momentum, we need to ensure we still apply friction as the current system is only doing this for positive speed.  To achieve this, add a check for &#8220;is speed is less than zero&#8221; and if so add to our speed until it reaches zero again.</p>
<pre class="brush: javascript; gutter: true">if(this.inputs.keyboard.up){
	if(speed&gt;0) speed = speed-0.1;
	if(speed&lt;0) speed = speed+0.1;
}</pre>
<p>The conversion of our existing &#8220;space game&#8221; into a &#8220;tank&#8221; game is now nearly complete. To finish off the conversion, we just need to give our tank its turret.</p>
<p>Adding the turret in a basic way should be fairly simple, so for now, let&#8217;s just create a new sprite object to be the turret (ensuring we have the correct offsets so that the turret part of our sprite image is all that is visible).</p>
<pre class="brush: javascript; gutter: true">turret = this.myturret = this.scene.Sprite("tank.png",{
	"layer": this.layer, //Layer tanks will be displayed in.
	"x": 100, 	//X position of sprite
	"y": 100, 	//Y position of sprite
	"w": 36, 	//width of sprite.
	"h": 59, 	//height of sprite.
	"xoffset":75,
	"yoffset":0,
	});</pre>
<p>Once that is done, we then need to add some code to keep our turret&#8217;s position in sync with the main tank. Under the &#8220;mytank.update();&#8221;, add the following code.</p>
<pre class="brush: javascript; gutter: true">this.myturret.position(nx,ny);
this.myturret.setAngle(ang);
this.myturret.update();</pre>
<p>With a little luck you should now have something along the lines of this:</p>
<div class="centre_zone"><a href="http://userbag.co.uk/demo/g1_demo/g_4/">Click to view demo 4</a></div>
<p>The next step is to give our tank the ability to aim it&#8217;s turret, so when bad guys finally do get added, we can shoot them.</p>
<p>As with the keyboard inputs, getting the mouse position in Sprite.JS is fairly simple and is somthing we can just ask spirte.js&#8217;s input object to give us. From this and the tank&#8217;s own X,Y coordinates, figuring out which way our turret needs to be angled to fire where we point shouldn&#8217;t actually be all that difficult (thanks to a handy little math function called <a title="Atan 2 Explination" href="http://en.wikipedia.org/wiki/Atan2#Illustrations" target="_blank">atan2</a>).</p>
<pre class="brush: javascript; gutter: true">//Get center point for the tank
tank_cent_y = this.mytank.y+(this.mytank.h/2);
tank_cent_x = this.mytank.x+(this.mytank.w/2);
//Work out angle that the cursor is from tank.
cursorAngle = Math.atan2(
	(this.inputs.mouse.position.y - tank_cent_y),
	(this.inputs.mouse.position.x - tank_cent_x)
 )+1.571;//Add roughly 90 degrees.</pre>
<p>Now we have the angle, we can pass it to the &#8220;myturrent.SetAngle&#8221; method, so that it&#8217;s aim will now follow the cursor (instead of just picking up the its angle from the tank hull as it is currently).</p>
<pre class="brush: javascript; gutter: true">this.myturret.setAngle(cursorAngle);</pre>
<p>Now we can aim our tank, it makes sense to give it the ability to fire. As with everything else so far, the first thing is to create the missile sprite, for laziness I just went with another quick &#8220;paint.exe&#8221; job:</p>
<p>&nbsp;</p>
<div class="centre_zone"><img src="http://userbag.co.uk/demo/g1_demo/g_7/missile.png" alt="Missile Sprite" /></div>
<p>Getting it into the game though, will be a little different to how the tank body/turret were added, as unlike them, chances are we are going to want lots of missiles, not just the one. Thus rather than storing each missile individually, we&#8217;ll need to keep track of them in an array.</p>
<p>First,  define a new array to hold all our missiles at the top of the engine object.</p>
<pre class="brush: javascript; gutter: true">this.missiles = [];</pre>
<p>Then create a new function we can call every time the tank fires, in order to create us a new missile. For simplicity&#8217;s sake I just called mine &#8220;fireMissile&#8221;.</p>
<pre class="brush: javascript; gutter: true">this.fireMissile = function(){
	//Code here
}</pre>
<p>Within this method,  we then want to add the code to generate a new sprite and to store it in to our missiles array.</p>
<pre class="brush: javascript; gutter: true">missile = this.scene.Sprite("missile.png",{
	"layer": this.layer,
	"w":4,
	"h":11,
	"angle": 0,
	"x": 0,
	"y": 0

});
this.missiles.push(missile);</pre>
<p>The complex bit here is now going to be working out where the missile  needs to be placed, in order to fire from our tanks turret. Getting the angle is the simplest task as we can just grab it from our turret.</p>
<pre class="brush: javascript; gutter: true">var a = this.myturret.angle;</pre>
<p>While the x and y coordinates are a little more complex, as although we could just grab the tanks x and y and use that, a missile suddenly appearing in the middle of the tank and flying out doesn&#8217;t really make much scene. Instead, we need to figure out the coordinates of the point thirty or so pixels in front of our tank in the direction that the turret is facing.</p>
<p>To start, we are still going to need to get the centre point.</p>
<pre class="brush: javascript; gutter: true">x = this.mytank.x+(this.mytank.w/2);
y = this.mytank.y+(this.mytank.h/2);</pre>
<p>Given that, we can then use the same bit of math we use to calculate tank momentum, in order to figure out where our missile is going to be thirty pixels away from the centre of the tank (travelling in the correct direction). I ended up tweaking this to twenty eight pixels as it seemed to  fit a little better.</p>
<p>My resulting &#8220;fireMissile&#8221; function ended up looking pretty much like this:</p>
<pre class="brush: javascript; gutter: true">this.fireMissile = function(){
	var a = this.myturret.angle;
	var x = (this.mytank.x+(this.mytank.w/2))+ (28 * Math.sin(a));
	var y = (this.mytank.y+(this.mytank.h/2))+ (28 * Math.cos(a))*-1;
	missile = this.scene.Sprite("missile.png",{
		"layer": this.layer,
		"w":4,
		"h":11,
		"angle": a,
		"x": x,
		"y": y
	});
	this.missiles.push(missile);

}</pre>
<p>In order to make clicking actually call the function, you then need to add the following line under the rest of the movement/input code in the run function:</p>
<pre class="brush: javascript; gutter: true">if(this.inputs.mouse.click) this.fireMissile();</pre>
<p>At this point you will probably notice that none of the missile sprites added to the game are actually showing up yet, this is because we haven&#8217;t yet added a mechanism to update (and therfore draw) the new sprites.</p>
<p>To do this the easiest option is to again create an additioal function, then ensure its called ever time the game loop runs, by adding code such as the following to the bottom of the run function.</p>
<pre class="brush: javascript; gutter: true">this.updateMissiles();</pre>
<p>Next you need to create the updateMissiles function in order to give the aforementioned code something to call. Effectively the purpose of the updateMissiles function will be to loop through all missiles contained in the &#8220;missiles&#8221; array, and apply any updates needed (movement, redrawing etc).</p>
<p>To implement movement, we can use the same technique we used to calculate our missiles initial location (and to move the tank itself around)  in order to calculate the missiles next position. This can then be applied to the sprite before &#8220;update()&#8221; is called to redraw the sprite in the new location.</p>
<pre class="brush: javascript; gutter: true">this.updateMissiles = function(){
	this.missiles.forEach(function(m){
		var x = m.x+ (6 * Math.sin(m.angle));
		var y = m.y+ (6 * Math.cos(m.angle))*-1
		m.position(x,y);
		m.update();
	});
}</pre>
<p>Although this works fine, it&#8217;s probably a good idea to add a little bit of functionality to clean up sprites we no longer need, as once a missile leaves the game area there&#8217;s not a lot of point keeping it updated, or indeed, in the game at all.</p>
<p>To do this we will need to be able to remove sprites from the &#8220;this.missiles&#8221; array in engine, meaning we need to ensure the engine is avaible outside the scope of the main game object. (As the .forEach() method will put us in its own scope). To do this simply define a variable called engine above of the engine function.</p>
<p>In order to calculate whether or not we now want to remove a missile, we will need to get it&#8217;s x and y position and check they are both above zero and not beyond the width or height of our game area. If it is, we will then want to call &#8220;remove()&#8221; on the sprite itself and then remove it from our missiles array.</p>
<pre class="brush: javascript; gutter: true">if(!(
	(m.x&gt;0 &amp;&amp; m.x &lt; m.layer.w) &amp;&amp;
	(m.y&gt;0 &amp;&amp; m.y &lt; m.layer.h)
)){
	m.remove();
	engine.missiles.splice(engine.missiles.indexOf(m),1);
}</pre>
<p>Assuming everything has gone to plan, you should now have a game that looks like this:</p>
<div class="centre_zone"><a href="http://userbag.co.uk/demo/g1_demo/g_5/">Click to view demo 5</a></div>
<p>So we have a tank, we can drive around and can shoot missiles. I guess the next thing on the agenda is to create something to fight. To start I quickly created a new sprite to use as our &#8220;bad guy aliens&#8221;.</p>
<div class="centre_zone"><img src="http://userbag.co.uk/demo/g1_demo/g_7/slug.png" alt="Tank Sprite" /></div>
<p>Then i added a additional array to our engine object so we have somewhere to keep track of them (essentially they are going to work in much the same way that missiles do now).</p>
<p>Under our &#8220;this.missiles&#8221; array, add a:</p>
<pre class="brush: javascript; gutter: true">this.monsters = [];</pre>
<p>Then create the outline of your new spawnSlug (which is my monster of choice) and updateMonster methods.</p>
<pre class="brush: javascript; gutter: true">this.spawnSlug = function(x,y){
//stuff here
}
this.updateMonsters = function(){
//stuff here
}</pre>
<p>Creating a new slug is going to be almost identical to how missiles are created. We just setup our monster sprite and add the result to our&#8221; monsters&#8221; array.<br />
The angle itself doesn&#8217;t really matter so I&#8217;ve just set it as one, and the x and y coordinates to spawn our new slug are passed in as parameters.</p>
<pre class="brush: javascript; gutter: true">this.spawnSlug = function(x,y){
	slug = this.scene.Sprite("slug.png",{
		"layer": this.layer,
		"w":16,
		"h":39,
		"angle": 1,
		"x": x,
		"y": y
	});
	this.monsters.push(slug);
}</pre>
<p>Since the slug sprite has a few steps of animation, it&#8217;s also a good time to make use of Sprite.js&#8217;s Cycle method, which essentially allows us to easily animate our sprite using the sprite panel we created. This is done by providing an array of steps, each consisting of the x and y offset we should apply to our Sprite panel and the duration each panel should display for. Once setup the Cycle can then be attached to the slug sprite.</p>
<p>In order to keep track of the new Cycle object, I&#8217;ve chosen to store it within the Sprite object itself in an attribute called animation.</p>
<pre class="brush: javascript; gutter: true">//Create slug sprite
this.spawnSlug = function(x,y){
	slug = this.scene.Sprite("slug.png",{
		"layer": this.layer,
		"w":16,
		"h":39,
		"angle": 1,
		"x": x,
		"y": y
	});
	//setup animation.
	slug.animation = scene.Cycle([
		[0,0,5],
		[16,0,5],
		[32,0,5],
		[48,0,5],
		[32,0,5],
		[16,0,5]
	]).addSprite(slug);
	this.monsters.push(slug);
}</pre>
<p>Now we can create slug sprites, the next step is to do something with them once they are in the game. As with the missiles this is done by iterating through the list of monsters and applying certain actions to each, before finally updating the sprite. It is useful to note that if you call update on a cycle (as stored in the m.animation) you no longer need to call update on the Sprite itself in order to apply any movement/rotation.</p>
<pre class="brush: javascript; gutter: true">this.updateMonsters = function(){
	//Loop through each monster sprite
	this.monsters.forEach(function(m){
		m.animation.next().update();
	});
}</pre>
<p>Now we can start adding some behaviours to our monster, for example making them slowly advance towards the player. Using &#8220;atan2&#8243; again, we can  figure out which direction our sprite needs to travel in in order to find our tank (in the same way that we did when working out which direction to point our turret.)</p>
<pre class="brush: javascript; gutter: true">var a = Math.atan2(
	(engine.mytank.y-m.y),
	(engine.mytank.x-m.x)
)+1.571;//90 degrees</pre>
<p>Using this angle we can then point our sprite towards the tank and, then using the movement code now powering both the tank itself and it&#8217;s missiles, give our monsters the ability to move. The full code may look something like:</p>
<pre class="brush: javascript; gutter: true">this.updateMonsters = function(){
	//Loop through each monster sprite
	this.monsters.forEach(function(m){
		var a = Math.atan2(
			(engine.mytank.y-m.y),
			(engine.mytank.x-m.x)
		)+1.571;
		//Work out new location
		var x = m.x+ (1 * Math.sin(a));
		var y = m.y+ (1 * Math.cos(a))*-1;
		//Apply changes
		m.position(x,y);
		m.setAngle(a)
		m.animation.next().update();
	});
}</pre>
<p>In order to test that everything is now working as we expect, we just need to add a little code to our game to spawn the new slug monsters at certain intervals.</p>
<pre class="brush: javascript; gutter: true">if((engine.ticker.currentTick % 200)==0){
	this.spawnSlug(400,-50);
}</pre>
<p>The above code will simply add a new slug monster, every 200 ticks of the game loop. Having monsters that want to eat our tank is all well and good, but not a lot of fun if we can&#8217;t shoot them. To start, lets add a hp variable to your tank sprite.</p>
<pre class="brush: javascript; gutter: true">this.mytank.hp = 5;</pre>
<p>And the same to your monsters, within the spawnSlug method. (I gave mine 2 hp)</p>
<pre class="brush: javascript; gutter: true">slug.hp = 2;</pre>
<p>Now comes the hard part, collision detection, fortunately for us, we don&#8217;t need to worry to much about this. Sprite.js helpfully comes packaged with its own collision detection system, stored in &#8220;lib/collison.js&#8221; . Adding this to our game, suddenly adds a host of useful &#8220;collidesWith&#8221; style methods for detecting collisions (no Math required).</p>
<pre class="brush: javascript; gutter: true">&lt;script type="text/javascript" src='../vendor/lib/collision.js'&gt;&lt;/script&gt;</pre>
<p>To make use of this, navigate back in to your &#8220;updateMonsters&#8221; method and under the code to apply sprite changes, add:</p>
<pre class="brush: javascript; gutter: true">//Detect collisions
col = m.collidesWithArray(engine.missiles);
if(col !== false){ //false means there were no collisions
	//Take 1 hp away from this monster.
	m.hp--;
	//If monster has less than 1 hp (0), remove it from the game.
	if(m.hp &lt; 1){
		//Remove sprite
		m.remove();
		//remove fictional sprite from our array
		engine.monsters.splice(engine.monsters.indexOf(m),1);
	}
	//remove missile
	col.remove();
	//remove missile from our array
	engine.missiles.splice(engine.missiles.indexOf(col),1);
}</pre>
<p>Essentally the above code checks to see whether the current monster has collided with any of the missiles  stored within the missiles array. If no collisions were detected then the &#8220;m.collidesWithArray()&#8221;  will return false and nothing will happen.</p>
<p>Alternately, if there was a collision between the current monster and a missile, 1 hp is removed from the monster and a check is done to ensure the monsters isn&#8217;t dead (if its hp is below 1 (as in 0)), if the monster turns out to be dead, it is then removed from the game. Once this is complete, the missile that hit the monster is then also removed from the game, regardless of whether the monster was killed.</p>
<p>If you play the game now, you should find you are able to shoot the slug monsters as they come towards you. Fun as this is, being invulnerable takes away from the satisfaction, so the next step will be to add a little danger.</p>
<p>Under the above collision code, add:</p>
<pre class="brush: javascript; gutter: true">//Has a monster got to your tank?
col_me = m.collidesWith(engine.mytank);
if(col_me !== false){
	//If so, remove the monster, and take 1hp away from your tank
	m.remove();
	engine.monsters.splice(engine.monsters.indexOf(m),1);
	engine.mytank.hp--;
	//Check to see if the tank is dead?
	if(engine.mytank.hp &lt; 1){
		engine.ticker.pause();
		alert("game over");
	}
}</pre>
<p>This code  does the same thing as the previous collision code, except it is checking for collisions between the current monster and your tank, taking away your hp and removing the monster whenever one gets to you. If your tank runs out of hp, &#8220;game over&#8221; is then triggered by pausing the game loop and displaying a &#8220;game over&#8221; warning.</p>
<p>Because spawning is currently quite predictable, I think it&#8217;s worth adding a slightly better spawning mechanism, just to make the direction the monsters come from a little less predictable, and to additionally add a slowly increasing level of difficulty to the game.</p>
<p>Create a new function called spawnMonster, with code that looks something like;</p>
<pre class="brush: javascript; gutter: true">this.spawnMonster = function(){
	//50% chance of spawning top/bottom or left/right
	if(Math.round(Math.random())==1){
		//If left or right, randomly choose a height to attach
		//our new monster at
		h = Math.floor(Math.random()*this.layer.h);
		if(Math.round(Math.random())==1){
			//attach right
			this.spawnSlug(this.layer.w+50,h);
		}else{
			//attach left
			this.spawnSlug(-50,h);
		}
	}else{
		//if top/bottom, figure out what width to add our sprite
		//at
		w = Math.floor(Math.random()*this.layer.w);
		if(Math.round(Math.random())==1){
			//at bottom
			this.spawnSlug(w,this.layer.h+50);
		}else{
			//at top
			this.spawnSlug(w,-50);
		}
	}
}</pre>
<p>The above code essentially flips a coin on whether the monster should spawn at the top/bottom or left/right of the game area. Then depending on which is picked, pick a random position on either the x or y axis (just off screen) to add a sprite. The side the sprite will spawn on is then selected by another coin flip (so to speak).</p>
<p>Once this is done, go to the &#8220;run&#8221; function and just above where the speed variable is being defined, define a second one and call it spawnrate. Set it to 200. Now within the run method itself, replace the previous monster spawning code with:</p>
<pre class="brush: javascript; gutter: true">//Spawn monster every time tick is a multiple of spawnrate
if((this.ticker.currentTick % spawnrate)==0){
	//If spawn rate is higher than 20, decrese it by 2.
	if(spawnrate&gt;20) spawnrate=spawnrate-2;
	//Spawn a monster somewhere
	this.spawnMonster();
}</pre>
<p>The new code will call the this.spawnMonster to create a new slug in a random location, every time the ticker equals a multiple of &#8220;spawnrate&#8221;. Additionally, each spawn, the time before the next spawn decreases slightly, meaning the monsters will begin to spawn at a faster and faster rate (until the maximum of one every 20 ticks is reached).</p>
<p>To finish off,  make sure to add all the new sprite images to your scene.loadImages back in your bootstrap function, just to avoid the game starting before all sprites have been loaded in to memory.</p>
<pre class="brush: javascript; gutter: true">scene.loadImages([
	'tank.png',
	'slug.png',
	'missile.png',
	 ], function() {</pre>
<p>Hopefully, if everything went to plan your game should now look and play something like this:</p>
<div class="centre_zone"><a href="http://userbag.co.uk/demo/g1_demo/g_6/">Click to view demo 6</a></div>
<p>Now the game is more a less playable and pretty much all our original goals have been completed. I just wanted to add a few final tweaks, that should hopefully make the game that little bit more enjoyable to play. 90% of this change just being the addition of a Score and the visibility of your hp.</p>
<p>To add the HP &amp; score box, I added the following html in to the page (under the game_map div).</p>
<pre class="brush: html; gutter: true">&lt;div id='score_board'&gt;
	&lt;div id='score'&gt;0&lt;/div&gt;
	&lt;div &gt;Health: &lt;span id='hp'&gt;5&lt;/span&gt;/5&lt;/div&gt;
&lt;/div&gt;</pre>
<p>Combined with the following CSS</p>
<pre class="brush: css; gutter: true">#score_board {position:absolute;width:100px;right:0;top:0;color:#fff;z-index:9999;}
#score_board div {text-align:center;}
#score{font-size:5em;font-weight:bold;}</pre>
<p>This just adds a div on the top right, with a big number to indicate the score and a smaller line of text to tell you your hp. To make both the HP &amp; score counter work, add a score attribute to the main game object (below &#8220;this.inputs&#8221;).</p>
<pre class="brush: javascript; gutter: true">this.score = 0;</pre>
<p>Then in the updateMonsters method, just below where we removed destroyed monsters from the game, add the following code.</p>
<pre class="brush: javascript; gutter: true">engine.score++;
document.getElementById('score').innerHTML = engine.score;</pre>
<p>Then, a little further down where hp is being deducted from your own tank (just under &#8220;engine.mytank.hp&#8211;;&#8221;) add</p>
<pre class="brush: javascript; gutter: true">document.getElementById('hp').innerHTML = engine.mytank.hp;</pre>
<p>to keep your HP in sync with the UI.</p>
<p>And last but not least, to make the loosing screen a little less annoying, replace the &#8220;game over&#8221; alert with:</p>
<pre class="brush: html; gutter: true">document.body.innerHTML ='&lt;div class="end"&gt;&lt;h1&gt;Game Over!&lt;/h1&gt;&lt;div&gt;Your Score: '+engine.score+'&lt;/div&gt;&lt;/div&gt;';</pre>
<p>And add the following bit of additional css to your styles:</p>
<pre class="brush: css; gutter: true">.end {
	background-color:#fff;
	color:#000;
	width:400px;
	text-align:center;
	margin-top:50px;
	padding:10px;
}</pre>
<p>With that complete, for the purposes of this tutorial. Your done! Congratulation, you should now have a simple tank game that looks more or less like this:</p>
<div class="centre_zone"><a href="http://userbag.co.uk/demo/g1_demo/g_7/">Tank Combat: Final.</a></div>
<p>Keep in mind, at this point the game is still really basic, so I encourage you to have a go at developing it further. Just as a few ideas of things you may want to consider adding:</p>
<ul>
<li>Sounds for when firing the cannon, driving and blowing up monsters.</li>
<li>More monsters types, and maybe some smarter monster behaviours.</li>
<li>High scores?</li>
<li>Some terrain, to drive around.</li>
<li>Mobile support (Sprite.js) adds some basic stuff for mobile, but the game would benefit a lot from a properly mobile oriented control system.</li>
</ul>
<p>All code seen in this tutorial and comprising the demos is released as Open Source under the MIT Licence. The source for all demos can be found <a href='https://github.com/thybag/HTML5-JavaScript-Game-Demos-Tests/tree/master/g1_demo'>here</a>.</p>
<p>Thanks for reading,</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2012. |
<a href="http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games-part-2/">Permalink</a> |
<a href="http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games-part-2/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making HTML5 games by someone who knows nothing about making games.</title>
		<link>http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games/</link>
		<comments>http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 21:42:40 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[HTML5 Games]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[browser based]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JavaScript game]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[new]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sprite.js]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=286</guid>
		<description><![CDATA[If your thinking about trying your hand at creating a HTML5 game, but have no game creation experince on which to draw, your probably in the same boat as me. Since, despite this limitation, I decided to start making  a HTML5 game anyway, I thought I may as well post about my experiences in the hope [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_306" class="wp-caption alignright" style="width: 226px"><img class="size-full wp-image-306" title="game" src="http://userbag.co.uk/wp-content/uploads/2011/12/game.png" alt="" width="216" height="203" /><p class="wp-caption-text">Fleet Command - a HTML5 Game</p></div>
<p>If your thinking about trying your hand at creating a HTML5 game, but have no game creation experince on which to draw, your probably in the same boat as me. Since, despite this limitation, I decided to start making  a HTML5 game anyway, I thought I may as well post about my experiences in the hope they are useful (or at least interesting) to other people.</p>
<p>My true first attempt to create a HTML5 game was a few months back when I decided I&#8217;d start hitting the keyboard and hope something worked. Over the following week  I slowly hacked together the outline of a more-a-less functional but totally unsustainable JavaScript based Asteroids style shoot-em up <a href="http://thybag.co.uk">game</a>. Although it never really went any where, I did  learn some pretty important lessons from the experience. The summarise them:</p>
<div style="padding: 20px 10px 10px 10px;">
<ul>
<li>Game loops are important and a set interval doesn&#8217;t quite cut it.</li>
<li>Object collision is hard - especially if you want to do it accurately and don&#8217;t wan&#8217;t to kill the computer running it.</li>
<li>Geometry &#8211; This stuff really does have a use.</li>
<li>If you plan to do anything clever with the game, you need to keep performance in mind from the get go. Its very easy to bring stuff to a crawl.</li>
<li>Sprites look better than triangles.</li>
</ul>
</div>
<p>Based on this, for my latest attempt at making a game (which is substantially more ambitious) I decided to actually have a proper think at how I planned to develop it. I even went so far as to think up a basic plot and doodle roughly how i wanted it all to look. Aside from this though, one of my first major actions was to have a look at some of the HTML5 Game Development frameworks out there, so as to save myself having to reinvent the wheel for the second time (Granted that for the purpose&#8217;s of this analogy my last &#8220;wheel&#8221; was more oval than circle).</p>
<p>It turns out there are actually  quite a lot of HTML5 Game Development frameworks out there, after trying a few though i ended up selecting <a href="https://github.com/batiste">Batiste&#8217;s</a> Spirte.js to be my starting point. The reasons for this are fairly simple, sprite.js is very lightweight,  it support&#8217;s webGL (I&#8217;m not actually making use of this, i just think its cool), it includes some great extras such as functions for path finding class &amp; collision detection (which you can include as needed) and even though the documentation is a little sparse, the code is easy to read and there are a load of useful examples included.</p>
<p>After finally deciding to go ahead with the game using sprite.js, I spend a good few hours playing around with it, reading its documentation and taking a look though the examples on offer. One of the first things I noticed was that features such as pausing a game, were actually added by sprite.js out of the box. Additionally there were also handy methods to access user input, load assets in to memory prior to the game starting and a host other other little bits &amp; bobs which help to make starting a new game much less painless.</p>
<p>After getting roughly to grips with the codebase, I decided I may as well start actually building my game. My initial aim was to try and replicate the functionality iIhad managed on my first foray in to HTML5 Game building territory. To do this I started off by creating a new HTML file, set up a basic HTML5 structure  (html,head,body kinda stuff, no real content) and added a JavaScript include to grab sprite.js itself, plus this code in the head:</p>
<div>
<pre class="brush: javascript; gutter: true">&lt;script type="text/javascript"&gt;
	var bootstrap = function(){
		//Create new Sprite.js Scene (effectively the Canvas that sprite js draws on to)
		var scene = sjs.Scene({'w':window.innerWidth, 'h':window.innerHeight});
		var layer = scene.Layer("game_layer");
		//Load images needed to display (ensure these images exist or it won't load)
		scene.loadImages([
			'ship.png',
	 		'background.png'
			 ],
		 function() {
	 		//Create instance of Engine (class i'm using to run the game)
	 		engine = new Engine(scene, layer);
	 		//Setup game loop via Sprite.js's ticker (calls engine's run method)
	 		ticker = scene.Ticker(function() { engine.run(); });
	 		//Pass ticker to engine
	 		engine.setTicker(ticker);
	 		//Start the ticker
	 		ticker.run();
		});
	}
	//Bootstap Game (when page is loaded)
	window.addEventListener("load", bootstrap, false);
&lt;/script&gt;</pre>
</div>
<p>The job of the above code is pretty much to set sprite.js up and then pass along all the important values to my &#8220;engine&#8221; class. Once the document has loaded and sprite.js has loaded its required assets, the engine class is instantiated, the ticker is created and finally everything gets set in motion with the call to ticker.run().  The most basic engine class that won&#8217;t crash should look something along the lines of:</p>
<pre class="brush: javascript; gutter: true">function Engine(scene, layer){
		//store scene and layer for later
		this.scene = scene;
		this.layer = layer;
		this.ticker = null;
		//Create our sprite
		this.myship = this.scene.Sprite("ship.png",{
			"layer": this.layer, //Layer ship will be displayed in.
			"x": 100, 	//X position of sprite
			"y": 100, 	//Y position of sprite
			"w": 37, 	//width of sprite.
			"h": 75 	//height of sprite.
		});

		//Add set ticker method to Engine
		this.setTicker = function(ticker){
			this.ticker = ticker;
		}

		//Create run method which will be called each time the
		//game loop runs.
		this.run = function(){
			//Apply sprites changes (in this case make
			//it so we can see it)
			this.myship.update();
		}
	}</pre>
<p>And running the above code should give you something that looks like <a href="http://userbag.co.uk/demo/g1_demo/g_1/" target="_blank">this</a>.</p>
<p>If all has gone to plan (it hasn&#8217;t died horribly) the next step is to make the game actually do something in its run loop. We can use the built in Inputs() Class to get our inputs from the user. To add this, just add the below code under the &#8220;this.layer = layer;&#8217; line in the engine class.</p>
<pre class="brush: javascript; gutter: true">this.inputs = scene.Input();</pre>
<p>The addition of the above code now means which can check for &#8220;this.inputs.keyboard.up&#8221; which will return true whenever the user hits the up arrow (or w) key. The same is true for when the down key is pressed, or the left and right arrow keys. Using this we can start making things happen when these keys are pressed, the simplest form of this I could think of was to simply hook each action up so that it alters ships current position by adding or subtracting from its x and y values. The result being that a user will then be able to move the ship around the game are using their arrow keys.</p>
<p>Once this was done, my updated run method looked much like this:</p>
<pre class="brush: javascript; gutter: true">	this.run = function(){
		//Get ships current x and y.
		nx = this.myship.x;
		ny = this.myship.y;
		//Update it depending on which keys are pressed.
		if(this.inputs.keyboard.left){
			nx -= 2;
		}
		if(this.inputs.keyboard.right){
			nx += 2;
		}
		if(this.inputs.keyboard.up){
			ny -= 2;
		}
		if(this.inputs.keyboard.down){
			ny += 2;
		}
		//Tell the ship
		this.myship.position(nx,ny);
		this.myship.offset(0,0);
		//Apply the changes
		this.myship.update();
	}</pre>
<p>Assuming everything went well running you game should now give you somthing along the lines of <a href="http://userbag.co.uk/demo/g1_demo/g_2/" target="_blank">this</a>.</p>
<p>So, now we have movement, but it isn&#8217;t really very space ship like movement. To make the movement a little more &#8220;space ship&#8221; like, my first action was to change the behaviour of the left and right arrow keys, so that the rotate the ship in a given direction, rather than just move it left or right. To do this,  grab the ships current angle and just add or subtract 2 degree&#8217;s depending on which way we want to turn the ship. The code may look like:</p>
<pre class="brush: javascript; gutter: true">	ang = this.myship.angle;
	//Update it depending on which keys are pressed.
	if(this.inputs.keyboard.left){
		ang = (-2*(Math.PI/180))+ang;
	}
	if(this.inputs.keyboard.right){
		ang = (2*(Math.PI/180))+ang;
	}</pre>
<p>One thing you probably noticed is the adding 2 degrees is a little more maths heavy than you would have guessed. The reason for this is that sprite.js uses radians rather than degrees to calculate the rotation of the ship. To convert from degrees to radians we need to multiply are degree value by PI/180 and then everything will work as expected. Once we have are 2 degrees in radian form, we simply add it to the current angle value to produce a new value for our ships rotation.</p>
<p>On its own though this won&#8217;t do a lot as we still need to tell the sprite we want it to rotate to the angle value we just worked out. To do this simply add the call to the setAngle method, passing it our value, before the sprites update method .update() is run.</p>
<pre class="brush: javascript; gutter: true">this.myship.setAngle(ang);</pre>
<p>With the addition of the above code and a little luck your ship should now rotate. The next step is going to be making the ship travel in the right direction when we hit the up button, something that&#8217;s going to take a little math to solve. Fortunately the required math has already been calculated, meaning all we need to do is to shove our own values in to the formula below.</p>
<pre>new_x += (movement * Math.sin(angle));
new_y += (movment * Math.cos(angle));</pre>
<p>So for the purposes of our code, our go forward method should look like: (Keep in mind the Y position is the distance from the top of the canvas, so we need to invert this value for it to make sense in the context of our game)</p>
<pre class="brush: javascript; gutter: true">	nx += (5 * Math.sin(ang));
	ny += (5 * Math.cos(ang))*-1;</pre>
<p>We now move in the right direction, but it still seems a little lacking. Whats needed is a way to keep track of momentum and for simplicity sake the easiest way to do this is just add a var called speed outside of the run loop and set it to 0. The next step is then to move the &#8220;forward&#8221; code out for the forward action and to the main body of the run method, so that it will be called every time the game loop runs. Inside the now empty forward if statments action, add the following code</p>
<pre class="brush: javascript; gutter: true">if(speed &lt; 5) speed = speed+0.5;</pre>
<p>This will essentially cause the speed value to be increased when you hit the forward button.(limiting it to a max speed of 5 pixels per game loop.) Additionally you now need to swap the 5 in the moment code to use your speed value instead (or you will constantly be moving at that speed).</p>
<p>Now you have momentum, its also probably also worth adding a way of slowing back down again. The simplest way to do this is to add a little code in to the down arrows action, that does pretty much the exact opposite of the forward keys action. For example</p>
<pre class="brush: javascript; gutter: true">if(speed &gt; 0) speed -= 0.5;</pre>
<p>Altogether your run loop should now look something like:</p>
<pre class="brush: javascript; gutter: true">	var speed =0;
	//Create run method which will be called each time the
	//game loop runs.
	this.run = function(){

		//Get ships current x and y.
		nx = this.myship.x;
		ny = this.myship.y;
		ang = this.myship.angle;

		//Update it depending on which keys are pressed.
		if(this.inputs.keyboard.left){
			ang = (-2*(Math.PI/180))+ang;
		}
		if(this.inputs.keyboard.right){
			ang = (2*(Math.PI/180))+ang;
		}
		if(this.inputs.keyboard.up){
			if(speed &lt; 5) speed = speed+0.5;
		}
		if(this.inputs.keyboard.down){
			if(speed &gt; 0) speed -= 0.5;
		}
		nx += (speed * Math.sin(ang));
		ny += (speed * Math.cos(ang))*-1;

		//Tell the ship
		this.myship.position(nx,ny);
		this.myship.setAngle(ang);
		this.myship.offset(0,0);
		//Apply the changes
		this.myship.update();
	}</pre>
<p>You can see the full code (so far) in action <a href="http://userbag.co.uk/demo/g1_demo/g_3/" target="_blank">here</a>.</p>
<p>I&#8217;m planning to create a series of posts on HTML5/JavaScript game making when I get the time, so with luck this is just the first of many such articles. Since I covered a lot of the basic set-up in this post, hopefully in my next one I&#8217;ll be able to make a little more headway in to the actual meat of the stuff.</p>
<p><a href='http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games-part-2/'>You can now view the next tutorial in this series here</a></p>
<p>Also, if your wondering how the game that inspired this tutorial is going, check out what I&#8217;ve got so far <a href="http://userbag.co.uk/fleet" target="blank">here</a>.</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2011. |
<a href="http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games/">Permalink</a> |
<a href="http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/development/making-html5-games-by-someone-who-knows-nothing-about-making-games/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Secret Santa</title>
		<link>http://userbag.co.uk/general/php-secret-santa/</link>
		<comments>http://userbag.co.uk/general/php-secret-santa/#comments</comments>
		<pubDate>Tue, 06 Dec 2011 23:08:00 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Santa]]></category>
		<category><![CDATA[Secret]]></category>
		<category><![CDATA[Secret Santa]]></category>
		<category><![CDATA[University]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=275</guid>
		<description><![CDATA[After a few years of neglect I decided it was about time I gave my ageing PHP Secret Santa App a bit of an update. The original, having been the result of a spur of the moment, hacked together reaction to the idea of running a CS Secret Santa between my friends (way back when [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_278" class="wp-caption alignright" style="width: 280px"><a href="http://userbag.co.uk/labs/santa/"><img class="size-medium wp-image-278 " title="secretsanta" src="http://userbag.co.uk/wp-content/uploads/2011/12/secretsanta-300x201.jpg" alt="Secret Santa ScreenShot" width="270" height="181" /></a><p class="wp-caption-text">PHP Secret Santa</p></div>
<p>After a few years of neglect I decided it was about time I gave my ageing PHP Secret Santa App a bit of an update.</p>
<p>The original, having been the result of a spur of the moment, hacked together reaction to the idea of running a CS Secret Santa between my friends (way back when in my second year of UNI), was as you may have guessed a pretty crappy implementation. The code was awful and the word awful just doesn&#8217;t capture just how bad the UI really was. Despite this, I&#8217;ve still somehow ended up running the script almost every time Christmas rolls come around.</p>
<p>My newer version of the script functions, effectively, the same as my original. Rather than taking the more common approach of putting the names in to two arrays, shuffling one, then joining em back together until no one ends up with themselves, I decided to stick with my original &#8220;names in a hat&#8221; style algorithm. Mostly just for nostalgia value. The implementation effectively mirrors its real world equivalent, with each user taking their turn to grab a value from the &#8220;hat&#8221; (array of users who need gifts buying from them)  and putting it back and taking another if they happen to get themselves. This continues until every user has someone to buy for. The one flaw with this plan is that when the final person comes to pick, if it so happens that the only person left in the &#8220;hat&#8221; is themselves, there a little stuck. My solution to this problem was essentially just to make them swap with another user. Which so far has worked pretty well <img src='http://userbag.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Once everyone has been assigned someone to buy for, the next step is just email everyone telling them who they have. It may not be the shortest, simplest or most straight forward solution, but I quite like it either way.</p>
<p>The next step of the Rebuild was to try and create a &#8220;slightly&#8221; nicer looking UI, although due to my terrible design skills I&#8217;m not sure how successful this was, but on the bright side, I found an excuse to make a JavaScript Add User button.</p>
<p>As normal the code can be found on my <a href="http://github.com/thybag/PHP-Secret-Santa">github</a> or you can use the live version here: <a href="http://userbag.co.uk/labs/santa/">http://userbag.co.uk/labs/santa/</a></p>
<p>Please feel free to ask questions, point out bugs/flaws or even just use the script for your own Secret Santa&#8217;s.</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2011. |
<a href="http://userbag.co.uk/general/php-secret-santa/">Permalink</a> |
<a href="http://userbag.co.uk/general/php-secret-santa/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/general/php-secret-santa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Read and write to SharePoint lists using PHP</title>
		<link>http://userbag.co.uk/development/php-read-write-sharepoint-lists/</link>
		<comments>http://userbag.co.uk/development/php-read-write-sharepoint-lists/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 13:49:47 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[lists]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[sharepoint]]></category>
		<category><![CDATA[sharepoint lists]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=254</guid>
		<description><![CDATA[Its been a while since I last blogged so I thought I may as well post an update. The main thing I plan to present is my, hopefully useful, PHP SharePoint API Class. The aim of the class is essentially to make interacting with the SharePoint Lists API a whole lot more straight forward and [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I last blogged so I thought I may as well post an update. The main thing I plan to present is my, hopefully useful, <a href="https://github.com/thybag/PHP-SharePoint-Lists-API">PHP SharePoint API</a> Class. </p>
<p>The aim of the class is essentially to make interacting with the SharePoint Lists API a whole lot more straight forward and allow PHP developers to talk with the Lists API without having to get there hands dirty with SOAP.</p>
<p>As with most stuff I create, its free under MIT licence and is being maintained on my <a href="https://github.com/thybag/">Github</a> account. At current the tool is fairly basic, although if I end up working on a SharePoint based project again I may take the opportunity to expand it further. If anyone spots any bugs or wants to add some features feel free to send em my way or just fork the github repo. Currently the SharePointAPI code is only capable of interacting with an existing SharePoint list and does not support creating new ones programmatically at this time.</p>
<p>You can grab the full source from: <a href="https://github.com/thybag/PHP-SharePoint-Lists-API">https://github.com/thybag/PHP-SharePoint-Lists-API</a></p>
<h3>Setting up the PHP SharePointAPI Object</h3>
<p>Using the SharePointAPI to read a SharePoint list is pretty straight forward. The first step is to create a new instance of the SharePointAPI object which requires a username and password (which it will authenticate with in order to interact with the lists) as well as the path to a local copy of the SharePoint Lists WSDL file. </p>
<p>You can normally grab the WSDL from: sharepoint.url/subsite/_vti_bin/Lists.asmx?WSDL</p>
<pre class="brush: php; gutter: true">$sp = new SharePointAPI('&lt;username&gt;','&lt;password&gt;','&lt;path_to_WSDL&gt;');</pre>
<h3>Reading from a Sharepoint List</h3>
<p>Once the SharePointAPI Object has been created, you can read from a list simply by calling:</p>
<pre class="brush: php; gutter: true">$sp-&gt;read('&lt;list_name&gt;');</pre>
<p>More advanced filtering is also possible, for example if you wanted to filter on surname = Smith and only return 5 results you would call:</p>
<pre class="brush: php; gutter: true">$sp-&gt;read('&lt;list_name&gt;', 5, array('surname'=&gt;'Smith'));</pre>
<p>You can filter on multiple parameters simply by adding extra values to the filter array. (currently only AND ing is possible)</p>
<p>All results are returned as associative arrays, calling print_r on the results of a $sp-&gt;read(&#8216;&lt;list&gt;&#8217;); is probably the best way to understand exactly what data is being returned.</p>
<h3>Writing to a SharePoint List</h3>
<p>Writing to a SharePoint list (or inserting a new list item) is equally straight forward. The data to be inserted is simply provided as an associative array to the function. For example to add someone called bob to a list you may use:</p>
<pre class="brush: php; gutter: true">$sp-&gt;write('&lt;list_name&gt;', array('forename'=&gt;'Bob','surname'=&gt;'Brown','pet' =&gt;'cat'));</pre>
<h3>Editing a SharePoint List Item</h3>
<p>To edit an existing SharePoint item the syntax is fairly similar to the above examples. The primary difference being that the ID of the record you wish to edit is also required. Assuming the ID for Bob&#8217;s record was 20, you could change his pet to dog with the following code:</p>
<pre class="brush: php; gutter: true">$sp-&gt;update('&lt;list_name&gt;','20', array('pet'=&gt;'dog'));</pre>
<h3>Deleting a SharePoint List Item</h3>
<p>Deleting a SharePoint list item also requires the ID of the record you wish to remove.</p>
<pre class="brush: php; gutter: true">$sp-&gt;delete('&lt;list_name&gt;','&lt;ID&gt;');</pre>
<p>&nbsp;</p>
<p>Thanks for reading <img src='http://userbag.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>P.S.  I&#8217;m now only one week away from starting my new job on the <a href="http://blogs.kent.ac.uk/webdev/">Kent Web Development team</a>. Woo <img src='http://userbag.co.uk/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2011. |
<a href="http://userbag.co.uk/development/php-read-write-sharepoint-lists/">Permalink</a> |
<a href="http://userbag.co.uk/development/php-read-write-sharepoint-lists/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/development/php-read-write-sharepoint-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSnip 0.5, a Portfolio Section and a little blog optimisation.</title>
		<link>http://userbag.co.uk/general/jsnip-and-a-portfolio-section/</link>
		<comments>http://userbag.co.uk/general/jsnip-and-a-portfolio-section/#comments</comments>
		<pubDate>Thu, 25 Aug 2011 23:00:52 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[carl]]></category>
		<category><![CDATA[holiday]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[jsnip]]></category>
		<category><![CDATA[lightbox]]></category>
		<category><![CDATA[optimisation]]></category>
		<category><![CDATA[portfolio]]></category>
		<category><![CDATA[rambling]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=236</guid>
		<description><![CDATA[As a result of a holiday in Slovenia (obligatory photo to the right), being a little busier than normal at work and a hint of having nothing interesting to post it appears it&#8217;s actually been quite a while since I last updated my blog. My solution as you may have noticed is this somewhat rambling posting purportedly providing interesting [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_237" class="wp-caption alignright" style="width: 310px"><img class="size-medium wp-image-237 jsnipLightBox" title="DSCF1622" src="http://userbag.co.uk/wp-content/uploads/2011/08/DSCF1622-300x224.jpg" alt="A Photo I took in Sloveina!" width="300" height="224" data-image="http://userbag.co.uk/wp-content/uploads/2011/08/DSCF1622-1024x768.jpg" /><p class="wp-caption-text">Sloveina</p></div>
<p>As a result of a holiday in Slovenia (obligatory photo to the right), being a little busier than normal at work and a hint of having nothing interesting to post it appears it&#8217;s actually been quite a while since I last updated my blog.</p>
<p>My solution as you may have noticed is this somewhat rambling posting purportedly providing interesting information and such.</p>
<p>Probably the most interesting update to the estimated two people that actually read this blog is the release of my latest version of JSnip. The new version includes with it an array of bug fixes and a brand new LightBox Snippet, along with a rather snazzy little zoom animation to go with it. As always you can get the full code on <a href='https://github.com/thybag/JSnip'>Github</a> and check out the new features on the <a href='http://userbag.co.uk/demo/jsnip/sample.htm'>sample page</a>.</p>
<p>Probably less interesting would be the fact I finally got a more or less functioning version of my portfolio page on-line (minus quite a few projects I lack pictures for). The best part of this being my site is now finally free from those pesky &#8220;coming soon&#8221; pages, and that I&#8217;ve also found somewhere to dump a little feed from my github.</p>
<p>Least interesting of all, but probably still quite a nice change for anyone who actually views these pages is that the blog should now be loading signifcantly faster thanks to the addition of WP Super Cache. (Previously page loads were taking a good ice age and a half which was kinda ridiculous)</p>
<p>P.S. Click the Holiday Image to the right to see the new JSnip Lightbox in action.</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2011. |
<a href="http://userbag.co.uk/general/jsnip-and-a-portfolio-section/">Permalink</a> |
<a href="http://userbag.co.uk/general/jsnip-and-a-portfolio-section/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/general/jsnip-and-a-portfolio-section/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript URL Parser</title>
		<link>http://userbag.co.uk/development/javascript-url-parser/</link>
		<comments>http://userbag.co.uk/development/javascript-url-parser/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 13:18:19 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=227</guid>
		<description><![CDATA[For science reasons I decided to write a simple JavaScript URL Parser this morning. The basic idea behind the function is to make it easier to extract the bits of a URL your interested in, be it the Port,  Host,  Protocol or even the value of a parameter in the query string. /** * URL Parse * A quick URL [...]]]></description>
			<content:encoded><![CDATA[<p>For science reasons I decided to write a simple JavaScript URL Parser this morning. The basic idea behind the function is to make it easier to extract the bits of a URL your interested in, be it the Port,  Host,  Protocol or even the value of a parameter in the query string.</p>
<pre class="brush: javascript; gutter: true">/**
 * URL Parse
 * A quick URL parsing function for JavaScript
 * @version 0.4
 * @author Carl Saggs
 */
function urlParse(url){
	var self = {};
	//Store full url
	self.url = url;
	//array to store params
	self.QueryParams = new Array();
	//Use DOM to get URL basics
	self.a = document.createElement('a');
	self.a.href = url;
	//Parse Query String
	q_seg = self.a.search.substring(1).split('&amp;');
	for(i=0; i&lt;q_seg.length;i++){
		s = q_seg[i].split('=');
		self.QueryParams[s[0]] = s[1];
	}
	//Extract the Port
	self.port = url.split('/')[2].split(':')[1];

	//Return Protocol in use
	self.getProtocol = function(){
		return self.a.protocol;
	}
	//Return Host
	self.getHost = function(){
		return self.a.host.split(':')[0];//Remove the port from the end
	}
	//Return Port
	self.getPort = function(){
		//Assume default port if none is set
		return  (self.port == null)
				? ((self.getProtocol=='https:')?443:80)
				: self.port;
	}
	//Return Path
	self.getPath = function(){
		return self.a.pathname;
	}
	//Get full Query String
	self.getQueryString = function(){
		return self.a.search;
	}
	//Get Query String as Array
	self.getQueryArray = function(){
		return self.QueryParams;
	}
	//Get value of parameter in query string
	self.getQueryParam = function(x){
		return self.QueryParams[x];
	}
	//Return original URL
	self.getURL = function(){
		return self.url;
	}
	//Get Fragment
	self.getFragment = function(){
		return self.a.hash.substring(1);//Remove # from start
	}

	//Return self
	return self;
}</pre>
<p>The function is designed to be pretty straight forward to use, calling the function will return the object containing all of the URLs attributes which can then be accessed by the provided get Methods. An additional advantage to having the function return an object is that you can chain the functions when it seems appropriate (as in the final example below).</p>
<pre class="brush: javascript; gutter: true">//Usage Demo
var test = urlParse("http://www.sub.domain.com:1337/test/sample.php?queryArg1=Hello&amp;queryArg2=Goodby");
alert(test.getQueryParam('queryArg2')); // "goodbye"
alert(test.getPort()); // "1337"
alert(test.getHost()); // "www.sub.domain.com"
alert(test.getPath()); // "/test/sample.php"
//Alterntive usage
alert(urlParse("http://test.com:17/?a=Cake&amp;b=Cheese").getQueryParam('a')); // "Cake"</pre>
<p>Anyways, hopefully someone will find it helpful <img src='http://userbag.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Feel free to request additional features / notify me of any bugs in the comments. You can now also find it on my <a href="https://github.com/thybag/UrlParse">GitHub</a>.</p>
<p>[Edit: 2011/10/07] The source code has been updated to fix the scoping bug mentioned by Rikky.</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2011. |
<a href="http://userbag.co.uk/development/javascript-url-parser/">Permalink</a> |
<a href="http://userbag.co.uk/development/javascript-url-parser/#comments">4 comments</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/development/javascript-url-parser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Introducing JSnip</title>
		<link>http://userbag.co.uk/development/introducing-jsnip/</link>
		<comments>http://userbag.co.uk/development/introducing-jsnip/#comments</comments>
		<pubDate>Sat, 02 Jul 2011 17:20:14 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[JSnip]]></category>
		<category><![CDATA[image switcher]]></category>
		<category><![CDATA[introduction]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[jsnip]]></category>
		<category><![CDATA[new]]></category>
		<category><![CDATA[overview]]></category>
		<category><![CDATA[show hode]]></category>
		<category><![CDATA[showHide]]></category>
		<category><![CDATA[snippet]]></category>
		<category><![CDATA[snippets]]></category>
		<category><![CDATA[tabs]]></category>
		<category><![CDATA[tabs box]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=196</guid>
		<description><![CDATA[GITHub and GIT seems to be all the rage these days so I decided it was about time I got myself an account and figured out what all the fuss was about. My problem with this plan was that I had nothing worthwhile to use it with. To solve this issue I finally got around [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_214" class="wp-caption alignright" style="width: 230px"><a href="http://userbag.co.uk/demo/jsnip/sample.htm"><img class="size-full wp-image-214" title="jsnip" src="http://userbag.co.uk/wp-content/uploads/2011/07/jsnip.png" alt="JSnip Sample" width="220" height="146" /></a><p class="wp-caption-text">JSnip Sample Page</p></div>
<p>GITHub and GIT seems to be all the rage these days so I decided it was about time I got myself an account and figured out what all the fuss was about. My problem with this plan was that I had nothing worthwhile to use it with. To solve this issue I finally got around to creating something that I&#8217;ve been contemplating making for a while now. I like to call it JSnip.</p>
<p><strong><a href="http://userbag.co.uk/demo/jsnip/sample.htm">JSnip</a></strong> is a lightweight JavaScript based Snipping package, aimed at those who want to add interactive elements to their webpages but lack the necessary JavaScript knowledge to do so.</p>
<p>If you know basic HTML then useing JSnip should be a snap. Just upload the JSnip.js and JSnip.css files to your server, import them in the head of your HTML document; probably using something along the lines of:</p>
<pre class="brush: html; gutter: true">&lt;link rel='stylesheet' href='jsnip.css' type='text/css' /&gt;
&lt;script type="text/javascript" src='jsnip.js'&gt;&lt;/script&gt;</pre>
<p>and JSnip is ready to go.</p>
<p>Adding Snippets to your page is as simple as adding a class name to an element. In fact that&#8217;s actually all you need to do. If you want a showHide box for instance, just type out something like:</p>
<pre class="brush: html; gutter: true">&lt;div class='jsnipShowHide' title='Title for your ShowHide' &gt;
Show Hide Content
&lt;/div&gt;</pre>
<p>and you&#8217;ll get:</p>
<div class="demoBox">
<div class="jsnipShowHide" title="Title for your ShowHide">Show Hide Content</div>
</div>
<p>Now, if you wanted the ShowHide to be open by default, all you would need to do is add an data-mode of &#8220;open&#8221; to the tag. Thus:</p>
<pre class="brush: html; gutter: true">&lt;div class='jsnipShowHide' title='Title for your ShowHide' data-mode='open' &gt;
Show Hide Content
&lt;/div&gt;</pre>
<p>will produce:</p>
<div class="demoBox">
<div class="jsnipShowHide" title="Title for your ShowHide" data-mode="open">Show Hide Content</div>
</div>
<p>Adding Tabs is no more difficult, a basic set of Tabs for example need consist of no more code than:</p>
<pre class="brush: html; gutter: true">&lt;div class='jsnipTabs'&gt;
	&lt;div&gt;
		&lt;h2&gt;Tab 1&lt;/h2&gt;
		Tab 1 Content! Add tab one content here.
	&lt;/div&gt;
	&lt;div&gt;
		&lt;h2&gt;Tab 2&lt;/h2&gt;
		Tab 2 Content! Add tab two content here.
	&lt;/div&gt;
	&lt;div&gt;
		&lt;h2&gt;Tab 3&lt;/h2&gt;
		Tab 3 Content! Add tab 3 content here.
	&lt;/div&gt;
&lt;/div&gt;</pre>
<p>to create a Tabs box such as the one below.</p>
<div class="demoBox">
<div class="jsnipTabs">
<div>
<h2>Tab 1</h2>
<p>Tab 1 Content! Add tab one content here.
</p></div>
<div>
<h2>Tab 2</h2>
<p>Tab 2 Content! Add tab two content here.
</p></div>
<div>
<h2>Tab 3</h2>
<p>Tab 3 Content! Add tab 3 content here.
</p></div>
</div>
</div>
<p>The image switcher snippet as seen in one of my past <a href="http://userbag.co.uk/development/image-switcher-snippet/">tutorials</a> has also made it into JSnip. Thus a list of images can be transformed</p>
<pre class="brush: html; gutter: true">&lt;div class="jsnipImageSwitcher" style="width: 400px;"&gt;
    &lt;img src="/demo/img/skunk.jpg" alt="A baby skunk!" /&gt;
    &lt;img src="/demo/img/otter.jpg" alt="An otter" /&gt;
    &lt;img src="/demo/img/bunny.jpg" alt="A Bunny Rabbit" /&gt;
&lt;/div&gt;</pre>
<p>into this, with only the above code.</p>
<div class="demoBox">
<div class="jsnipImageSwitcher" style="width: 400px;"><img src="http://userbag.co.uk/demo/img/skunk.jpg" alt="A baby skunk!" /><img style="display: none;" src="http://userbag.co.uk/demo/img/otter.jpg" alt="An otter" /><img style="display: none;" src="http://userbag.co.uk/demo/img/bunny.jpg" alt="A Bunny Rabbit" /></div>
</div>
<p>Check out the <a href="http://userbag.co.uk/demo/jsnip/sample.htm">Sample page</a> to see how these snippets can be used together on a page.</p>
<p>The provided snippets are all nestable so they can be placed inside one another as much as you please, along with any other HTML you wish to add. A nice example of this is if you wanted to make the images in an ImageSwitcher link to a number of other webpages. All you would need to do is wrap the relevant image in a standard A tag pointed at where you want it to go.</p>
<p>The CSS behind the snippets can easily swapped out or modified to fit in with your own layout (as the snippets have been for this blog for instance), making the snippets simple to customise.</p>
<p>For anyone interested in the code, you can view it on my <a href="https://github.com/thybag/JSnip">GitHub repo</a>. I shall be creating another blog article soon, aimed at developers, explaining how it all works behind the scenes.</p>
<p>I&#8217;d be more then happy to answer any questions you may have in the comments section below. </p>
<p>Thanks for reading,<br />
Carl</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2011. |
<a href="http://userbag.co.uk/development/introducing-jsnip/">Permalink</a> |
<a href="http://userbag.co.uk/development/introducing-jsnip/#comments">No comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/development/introducing-jsnip/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create a mobile version of your site with just CSS!</title>
		<link>http://userbag.co.uk/development/create-a-mobile-version-of-your-site-with-just-css/</link>
		<comments>http://userbag.co.uk/development/create-a-mobile-version-of-your-site-with-just-css/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 20:53:55 +0000</pubDate>
		<dc:creator>Carl</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[CSS3]]></category>
		<category><![CDATA[Media Queries]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://userbag.co.uk/?p=181</guid>
		<description><![CDATA[A few week&#8217;s or so back Luke was showing off his new Responsive CV at work, which had the rather cool feature of instantly resizing itself to fit pretty much any screen size &#8211; even mobile. The magic behind all this, rather than any nifty bit of JavaScript, tuned out to be CSS Media Queries, [...]]]></description>
			<content:encoded><![CDATA[<p>A few week&#8217;s or so back <a rel="met colleague friend" href="http://www.red-root.com">Luke</a> was showing off his new <a href="http://www.red-root.com/design/a-responsive-cv/">Responsive CV</a> at work, which had the rather cool feature of instantly resizing itself to fit pretty much any screen size &#8211; even mobile. The magic behind all this, rather than any nifty bit of JavaScript, tuned out to be CSS Media Queries, a CSS feature I&#8217;d never really paid much attention to beforehand.</p>
<p>The basic idea behind CSS Media Queries is to give web developers the power to tell the browser to apply extra CSS when certain conditions are met. The most useful condition in regards to creating a mobile version of your site website the being browser width&#8217;s. As a rough example of how they work, imagine for example you have a website with a default width of 1000px and a user then resizes their browser window to 950px wide.</p>
<p>Using the following code snippet, once the users browser window has been resized to below 1000px the enclosed CSS will be instantly applied to the page, changing the containers width to 900.</p>
<pre class="brush: css; gutter: true">@media only screen and (max-width: 1000px) {
	#container {width:900px !important; }
}</pre>
<p>The real advantage&#8217;s of Media Queries over a standard fluid layout start to show up when you get to the significantly different screen resolutions, for example the 320px width of a mobile phone browser. Since Media Queries allow you to selectively apply whole chunks of additional CSS, you can use it to totally rearrange elements on the page in order to ensure your site remains functional at any resolution. Have a go at resizing this site for instance, the first big change to happen is the removal of the sidebar (at 720px), which coincides with the search bar being moved up to the top. The next big one happens when the site is transformed fully in to the mobile site (at 450px) which has quite substantially different styling to the normal view.</p>
<p>If you want to apply your mobile site CSS to any screen resolution below 350px, your code my look something like this.</p>
<pre class="brush: css; gutter: true">@media only screen and (max-width: 350px) {
	#container {width:320px !important; }
	/* Mobile Site CSS here */
}</pre>
<p>Or, if you want to resize headings on any resolution between 600px and 800px, your code may be as follows:</p>
<pre class="brush: css; gutter: true">@media only screen and (min-width: 600px) and (max-width: 800px) {
	h1 {font-size:0.0em;}
	/* More styles */
}</pre>
<p>As you can see, using this technique it becomes relatively straight forward (assuming you already have a good grasp of CSS) to create a mobile version of your site by just altering and adjusting a few of its styles.</p>
<p>One thing you may notice though, is that even if your Mobile Site styles work fine when you resize your browser window to the correct size, your actual mobile phone&#8217;s browser still shows the desktop version.</p>
<p>In order to get your mobile CSS styles to be applied correctly, its important to tell the mobile browser that you want everything rendered at its real size (as opposed to the zoomed out view they normally try to adopt when encountering desktop sites).</p>
<p>To do this, you&#8217;ll need to ad a veiwport meta tag to your websites header;</p>
<pre class="brush: html; gutter: true">
&lt;meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /&gt;
</pre>
<p>Once that&#8217;s done your mobile CSS should start showing up on your phone just as you would expect it to.</p>
<p>Having only recently added CSS Media Queries to this site, I&#8217;m still incredibly impressed with them. CSS Media Queries turn the rather substantial job of creating an alternate mobile friendly version of your site in to about half an hour&#8217;s CSS. Awesome, no?</p>
<hr />
<p>Please note that tutorial example's will not work in feed readers as they rely on a number of JavaScript files being available. To view the tutorial as it should be seen head over to <a href='http://userbag.co.uk'>Userbag.co.uk</a>.</P>
<p><small>© Carl for <a href="http://userbag.co.uk">Userbag.co.uk</a>, 2011. |
<a href="http://userbag.co.uk/development/create-a-mobile-version-of-your-site-with-just-css/">Permalink</a> |
<a href="http://userbag.co.uk/development/create-a-mobile-version-of-your-site-with-just-css/#comments">One comment</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://userbag.co.uk/development/create-a-mobile-version-of-your-site-with-just-css/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 4.135 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-21 00:28:49 -->

