Posts in "Tutorials"

Making HTML5 games by someone who knows nothing about making games.

Fleet Command - a HTML5 Game

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.

My true first attempt to create a HTML5 game was a few months back when I decided I’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 game. Although it never really went any where, I did  learn some pretty important lessons from the experience. The summarise them:

  • Game loops are important and a set interval doesn’t quite cut it.
  • Object collision is hard – especially if you want to do it accurately and don’t wan’t to kill the computer running it.
  • Geometry – This stuff really does have a use.
  • 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.
  • Sprites look better than triangles.

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’s of this analogy my last “wheel” was more oval than circle).

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 Batiste’s Spirte.js to be my starting point. The reasons for this are fairly simple, sprite.js is very lightweight,  it support’s webGL (I’m not actually making use of this, i just think its cool), it includes some great extras such as functions for path finding class & 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.

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 & bobs which help to make starting a new game much less painless.

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:

<script type="text/javascript">
	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);
</script>

The job of the above code is pretty much to set sprite.js up and then pass along all the important values to my “engine” 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’t crash should look something along the lines of:

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();
		}
	}

And running the above code should give you something that looks like this.

If all has gone to plan (it hasn’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 “this.layer = layer;’ line in the engine class.

this.inputs = scene.Input();

The addition of the above code now means which can check for “this.inputs.keyboard.up” 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.

Once this was done, my updated run method looked much like this:

	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();
	}

Assuming everything went well running you game should now give you somthing along the lines of this.

So, now we have movement, but it isn’t really very space ship like movement. To make the movement a little more “space ship” 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’s depending on which way we want to turn the ship. The code may look like:

	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;
	}

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.

On its own though this won’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.

this.myship.setAngle(ang);

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’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.

new_x += (movement * Math.sin(angle));
new_y += (movment * Math.cos(angle));

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)

	nx += (5 * Math.sin(ang));
	ny += (5 * Math.cos(ang))*-1;

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 “forward” 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

if(speed < 5) speed = speed+0.5;

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).

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

if(speed > 0) speed -= 0.5;

Altogether your run loop should now look something like:

	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 < 5) speed = speed+0.5;
		}
		if(this.inputs.keyboard.down){
			if(speed > 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();
	}

You can see the full code (so far) in action here.

I’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’ll be able to make a little more headway in to the actual meat of the stuff.

You can now view the next tutorial in this series here

Also, if your wondering how the game that inspired this tutorial is going, check out what I’ve got so far here.

Read and write to SharePoint lists using PHP

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 allow PHP developers to talk with the Lists API without having to get there hands dirty with SOAP.

As with most stuff I create, its free under MIT licence and is being maintained on my Github 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.

You can grab the full source from: https://github.com/thybag/PHP-SharePoint-Lists-API

Setting up the PHP SharePointAPI Object

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.

You can normally grab the WSDL from: sharepoint.url/subsite/_vti_bin/Lists.asmx?WSDL

$sp = new SharePointAPI('<username>','<password>','<path_to_WSDL>');

Reading from a Sharepoint List

Once the SharePointAPI Object has been created, you can read from a list simply by calling:

$sp->read('<list_name>');

More advanced filtering is also possible, for example if you wanted to filter on surname = Smith and only return 5 results you would call:

$sp->read('<list_name>', 5, array('surname'=>'Smith'));

You can filter on multiple parameters simply by adding extra values to the filter array. (currently only AND ing is possible)

All results are returned as associative arrays, calling print_r on the results of a $sp->read(‘<list>’); is probably the best way to understand exactly what data is being returned.

Writing to a SharePoint List

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:

$sp->write('<list_name>', array('forename'=>'Bob','surname'=>'Brown','pet' =>'cat'));

Editing a SharePoint List Item

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’s record was 20, you could change his pet to dog with the following code:

$sp->update('<list_name>','20', array('pet'=>'dog'));

Deleting a SharePoint List Item

Deleting a SharePoint list item also requires the ID of the record you wish to remove.

$sp->delete('<list_name>','<ID>');

 

Thanks for reading 🙂

P.S.  I’m now only one week away from starting my new job on the Kent Web Development team. Woo 😀

Create a mobile version of your site with just CSS!

A few week’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 – 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’d never really paid much attention to beforehand.

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’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.

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.

@media only screen and (max-width: 1000px) {
	#container {width:900px !important; }
}

The real advantage’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.

If you want to apply your mobile site CSS to any screen resolution below 350px, your code my look something like this.

@media only screen and (max-width: 350px) {
	#container {width:320px !important; }
	/* Mobile Site CSS here */
}

Or, if you want to resize headings on any resolution between 600px and 800px, your code may be as follows:

@media only screen and (min-width: 600px) and (max-width: 800px) {
	h1 {font-size:0.0em;}
	/* More styles */
}

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.

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’s browser still shows the desktop version.

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).

To do this, you’ll need to ad a veiwport meta tag to your websites header;

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

Once that’s done your mobile CSS should start showing up on your phone just as you would expect it to.

Having only recently added CSS Media Queries to this site, I’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’s CSS. Awesome, no?

JavaScript eyes that follow the cursor.

I remember one of the first tutorials I wrote back on my old thybag website was on how to get eyes that follow the cursor using Flash. I’d initially worked out how to do it in order to animate the alien in my banner a little and although the effect can be a little disconcerting at times, I kinda liked it.

For that reason I decided to set myself the challenge of getting the functionality back, only this time using JavaScript instead of flash. Rather than waste space with extra images I also decided I may as well draw the eyes with canvas while I was at it.

The aim of this little tutorial will be to show you how to create something like this.
(Though you will more likely want to use your own image.)

If your not really intested in how its done and just want the script, feel free to grab it from here. You can create eye’s by calling

//Variables are just used to make it obvious what each parameter is, 
//you can call the functions with the param's directly if you prefer.
var positionFromLeft = 200;
var positionFromTop = 50;
var eyeSize = 30;
var appendEyetoDivNamed = 'mydiv';
new alienEye(positionFromLeft,positionFromTop,eyeSize,appendEyetoDivNamed);

If your interested to see how the eyes following the cursor script works, keep reading after the jump.

Read the rest of this post »

Image-switcher snippet


Since my plan today was to start working on creating the portfolio/past work section of this site, I decided to start by creating a few simple snippets that I thought would likely come in handy.

The first of these being a simple image switcher. The idea behind the snippet was pretty much to just be able to put some images inside a div with a particular class and have the snippet do all the work. A little bit of dojo later and the below is the result.

A baby skunk!An otterA Bunny RabbitUpside down SealA Kitten sleeping next to a big dog

(images “borrowed” from the interweb)

To use the snippet all you need to add Dojo to the page, then import the jsnippet CSS and JavaScript files. After that just add a div to the page with the class “jsnipImageSwitcher”. The above Image switcher for instance is actually just the following HTML wirtten in to the page.

<div class="jsnipImageSwitcher" style="width: 400px;">
    <img src="/demo/img/skunk.jpg" alt="A baby skunk!" />
    <img src="/demo/img/otter.jpg" alt="An otter" />
    <img src="/demo/img/bunny.jpg" alt="A Bunny Rabbit" />
    <img src="/demo/img/seal.jpg" alt="Upside down Seal" />
    <img src="/demo/img/kittendog.jpg" alt="A Kitten sleeping next to a big dog" />
</div>

The snippet will work out the amount of images dynamically so there are no limits to how many can be used within it. The only limitation to the above being that the default styles may not leave room to fit the dots. As you may have noticed the snippet also pulls it’s caption from the images alt attribute, which has the added bonus of improving the images ability to be found by search.

If for any reason JavaScript is not enabled in a user’s browser the images will display normally without any side-effects as a result of being part of the snippet. The snippet is tested in Firefox, Chrome and IE9.

If your interested in knowing how the snippet works, keep reading after the jump for a full explanation.

Read the rest of this post »