A selection of screens from my new HTML5 arcade game – Road Rage

I intend to complete this game very soon. I confess I’ve got a little carried away adding some special effects with sprites. The shards of metal that fly away from the damaged vehicles when struck with a missile or gun fire were just too tempting to resist.
I spawn them in the game with random trajectory, speed and spin rate. The effect is pretty neat. For the most part the metal shards whizz off the screen but occasionally you get a slower shard that just ambles off screen with a slow spin. It really adds to the impression of blasting everything to pieces. Hope to have the game completed over the Christmas break in time for new year.

9HTML5 arcade game screenshotHTML5 arcade game screenshotHTML5 arcade game screenshotHTML5 arcade game screenshotHTML5 arcade game screenshotHTML5 arcade game screenshotHTML5 arcade game screenshotHTML5 arcade game screenshot

Balancing the action and using a classic for inspiration

Designing HTML5 arcade games with JavaScript has become something of a theraputic exercise. The combined thrills of pixelling, coding and designing the various elements of the action are proving to be quite useful in the stressful run up to Christmas.
Yet despite this I now find myself in that unavoidable “crunch” mode on two projects. I also set a target to finish these two projects by the new year.

A laugh at it now but I shelved my first project as it approached completion to pursue a fresh project. It was of course a diversion. I was deliberately avoiding the pain of that final 10% that takes an agonising amount of time to complete. Now I have doubled the pain!

It’s not all bad.
The discipline of developing arcade games has evolved and tightened over the years to become almost formulaic. This in itself isn’t always a good thing but it can be useful to have a blueprint for design when it comes to balancing, testing and code fixing.

For the most part at this stage I find that the raw code is cut and I’m largely playing with numbers. I play the games A LOT and talk to myself as I’m running through them – always making notes. Here’s such a conversation :)

There’s just not enough to challenge me here. The player character moves too quickly to be threatened by the bad guys. The bad guys need to target the player more. There’s too much room to move. The player isn’t developing any skills in his movement and bullet / entity dodging!

I kid you not. This was a recent note I took.
The beauty of all of this is that everything in the game is defined by numerics. The player’s movement is defined as a speed parameter that allows his co-ordinates to increment each tick. Similarly the other objects in the game perform against the same calculations. In the driving / shooting game (which I currently call Road Rage) the room in which the player has for movement is defined by the road object’s width and height. I applied a .nextthink attribute to the road container which ticks down every game tick. At zero I make another decision on how to scale and move the road.
With this method I can shrink or expand the road with ease after an elapsed amount of time. As a result of my testing and observations above I could see that the road needed to narrow more frequently. The player’s car going “offroad” results in a lot of damage and consequently Game Over so a shrinking road is a real challenge to the player.

HTML5 arcade game

As you can see in the screenshot the road is divided up in to slices. Each “slice” is an object that contains parameters for the ground texture, the road, the road’s verge and the lines that run down the middle.
The only artwork on display per slice is the ground and verge. The other two elements are solid colour blocks.

The tree decorations that overlay the ground are sprite objects and behave in a default sprite behaviour. i.e. emerge off screen, run the length and disappear without any collision detection.

Developing the shifting road wasn’t really much of a challenge. You could almost imagine the process as a series of around a dozen rectangular cards placed in order. By altering the x position of each road object as it is spawned off the top of the canvas (and subsequently allowing the object to increment its co-ordinate) you can create a satisfactory rippling effect that simulates the shifting road. The road width (the solid colour area) is known and therefore I can plot x co-ordinates for the overlayed verges.
Similarly any sprite object that sits on the road can be tested to see whether it has over-run the verge in which case I apply damage to it. Too much damage and it is destroyed. The impact on the random military vehicles in the game is a key part of the appeal as the player’s gleaming red sports car (modelled on a Ferrari 458!) can bump them off the road with a few well timed swerves in the right direction :)

For a long time in the early days of development I was playing the game and struggling to find a core mechanic for it. That vital element of the game that forms the player’s goal or goals. I knew that arming a sports car with rockets and allowing it to shunt other vehicles off the road would be fun, but as always I wanted an intensity to the action that meant there would be a ton of rockets and bombs on the screen. This can cause design problems in terms of setting a challenge since firing a huge amount of rockets and lasers only works if the stuff you’re aiming at is destroyed! It’s no good if the targets just bounce around a bit and are unaffected by your gunfire.

So I dabbled with all sorts of mechanics including collecting valuable items and avoiding oil slicks. They just didn’t work. The thrill of the game is in its pace and causing the car to spin or forcing the player to swerve and collect items just didn’t add up to very much fun. It needed to be a high octane experience with shooting, dodging, turboing and explosions set against an underlying need for speed.

So I fired up Out Run for a little inspiration. A wonderful game from the 1980s in which you drive a car at speed across an undulating terrain whilst avoiding other road users. The game is divided in to stages such that when you cross a checkpoint you are rewarded with a little more time to play.
This did it for me. It was obvious. A game in which you drive a car has to be a challenge of beating the clock.

I could still get away with blasting the bad guys I just needed to ensure that the core goal was to complete each stage in a set amount of time. Adding a timer was simple. I set it to 30 seconds initially and ticked down every second. At zero the car exploded and the game was over.

So the next question was how do I speed the car up and slow it down without having specific controls overlaid on the touchscreen.
This was a no-brainer. I implemented a turbo accumulator. The destruction of cars and military vehicles spawned turbo collectables that bounced around the screen. By collecting several of these the player built up their turbo bar sufficiently to engage a short (10 second) turbo mode in which the car’s speed doubled. The faster the car the quicker the player zoomed through each stage. So there was plenty of incentive for the player to destroy the other vehicles and go collecting the turbo shards.

But this wasn’t enough of a challenge. I wanted to add an element of dodging to the game so I stuck with the idea of the other vehicles launching missiles at the player. One hit and the car was destroyed! Unlike off-road damage or bumping the other cars, missile damage didn’t reduce the player’s “health”. It just wiped them out.

So I’m now confident that I have the game that I was after. As I play it now it’s pretty close to the original design and with the injection of the pulsating soundtrack and over-the-top sound effects I think it’s easily the best arcade game I’ve made to date.

I look forward to sharing it within the PlayStar Arcade shortly.

Sprite creation for mobile web games – some thoughts on colour and composition

Back in my day as a Gameboy Advance artist we used to have some key rules for asset creation. Generally much of the design was handled externally via the client and we simply adapted any work for presentation on the small screen. But occasionally we were given some free reign to create new art. To achieve optimal presentation on the GBA screen – which don’t forget was not back lit! – we needed to use the brighter end of the spectrum. Few games on the GBA got away with using the darker palettes. I always thought that the Castlevania games let themselves down in this respect. Fine games in many respects but a dog to play without any additional light on the screen.
By contrast a game like Mario with its brighter colours obviously lends itself to the console’s display limitations.

Castlevania (left) and Super Mario Advance

Castlevania (left) and Super Mario Advance

In defining the graphics for my HTML5 arcade games I try to keep this simple rule in mind. I don’t need to. My target platforms are mobile and of course the world of mobile displays has improved no end. We now have elaborate screens in which each pixel is infact its own light source. Powerful stuff and extremely rich for the game experience. I could in theory get away with much darker palettes but there’s something about vibrant colours that I think is more attractive and more appealing to the gamer. It’s engrained in to me to use rich colour in games and it’s not something I want to turn my back on.

I remember as a young bedroom coder back in the early 1980s reading a copy of C&VG. In it gaming legend Jeff Minter wrote paragraphs about the importance of colour in games. He argued that people respond to colour in a far more powerful way than they do muddy or darker colours. Certainly for arcade games (which is of course Jeff’s forte) this is true and back then on systems like the C64 and Atari 800 range rich colours were a key feature.

So much like the GBA days I start out by defining a palette. For this I use Photoshop. It’s not the best palette tool in the world but it allows for a selection of colours that can be used across the game’s assets.
I start out by using the colour picker and heading for the top right corner for the brighter colours.

Photoshop colour picker

Photoshop colour picker

I try to visualise in my mind how the colours will separate across the game screen.
I am trying to picture the player’s on-screen character sat on top of the game’s backdrop and sitting alongside the other key game elements. This helps to define the colours that I will add to the palette – or swatch in Photoshop parlance.

Photoshop swatch

Photoshop swatch

Dropping new colours in to the swatch is simple and you can quickly build up a bunch of saved colours.
I skip down the spectrum in the colour picker and pick out the colours that I think will best suit the sprites, backdrop and effects. I also try to bear in mind additional colours that could be used as highlights or shadows.
For example, if I want a shiny glass ball sprite it’s useful to have colours nearer to white to add as a highlight.
I try to keep the palette to no more than 16 colours. It’s not always such an easy thing to achieve but it’s a good discipline to aim for.

For my current platform game project colour selection is quite simple. The main character is a squirrel and I’ve coloured him a nice vibrant orange with some light brown. It makes sense to me to have him sat on top of a blue hue since blue and orange compliment one another and always look appealing. But rather than have the blue sat in the same luminance range as the squirrel’s oranges I tone it down a bit. Something a bit more pastel-like.

squirrel sprite

Squirrel against two blues

I try to ensure that there is a clear visual separation between these “layers”. The foreground “active” layer if you like and the background layer.
For every other active game element (or sprite) I try to adopt the same rule. It helps to identify to the gamer which items in the game are important. There are countless other ways to achieve this but this is a good start.

html5 game screenshot

Platform game dev screenshot

Lately I’ve taken to adding a dark key line around the game’s sprites. In fact with the platform game I deliberately designed the game to use cute cartoon characters so that I could achieve this. It really lifts the sprites up from the background layer and for me is a neat style for mobile arcade games.

Within each sprite I also like to define key areas with a darker colour.
So for example with the squirrel you can see that I’ve separated visually his eye, arms, nappy and feet. This is important as it helps to create the illusion of movement and animation. If I’d merely used variations on the oranges and browns it’d be less easy to pick out the swinging arm and walking feet.

I adopt the same approach to any special effects that I use. Things like puffs of smoke and explosions. These are all foreground elements and need to be separated from the background. Again the explosions use the red / orange / yellow end of the spectrum which sits on top of blue nicely. Similarly yellow stars and white smoke will be clearly visible to the gamer and act more as visual rewards than anything else. Much like the character sprites I’ve taken to adding a key line to help separate them.
I’m a seasoned cartoonist so being able to pixel cartoons for these casual games is a huge thrill!

Hopefully that gives a quick insight in to my thought processes for creating the colour palettes in my HTML5 games.
In future posts I’d like to discuss sprite composition and scale in more detail and will also touch on how to create simple animation effects.

Super Jet Boy – a few thoughts on touch-screen control and sprite presentation

Jet Boy (or Super Jet Boy to give it its full title) is a game about a boy with a rocket pack who embarks on an adventure to recover some mystical golden statuettes. High above the kingdoms of his homeworld a series of enchanted sky temples play host to an array of weird monsters charged with one simple task – protect their master’s golden treasure.

jetboy3 jetboy1

Jet Boy has no special powers. For once I resisted the urge to load my game character up with bombs & lasers and throw explosions around the screen. All I wanted with Jet Boy was a simple case of learning how to control a character with a rocket pack.

Much of the work in creating the game was already written thanks to my work on Crossfire.
In that game I defined a pretty neat way of designing challenges using my own tools that ultimately spat out some JavaScript with enough data to construct a level. The logic for actually assembling that level and its obstacles and entities is elsewhere within the game’s core.
I pretty much lifted most of that logic when constructing Jet Boy and adapted it to respond to gravity and bi-directional movement.

The real challenge in developing the game was in the control of the main character.
I knew that I wanted movement in all directions and also the concept of thrust to lift the character higher up the level. When no thrust was applied (either through no screen press or lack of fuel) the character would simply fall until they reached the base of the level. At this point the player would be looking for bonus ballons carrying fuel to re-enable the rocket pack.

So how do you acheive all of this without using on-screen buttons in a touch screen environment?

The obvious conflict was in the distinction between simply touching the screen to move the character and touching the screen to apply thrust to the rocket pack. As soon as I tap the screen both would apply. I may only want to shift the character from left to right in a horizontal fashion but by virtue of the fact I’m touching the screen the rocket pack would fire and the character would raise.
I initially figured this would be acceptable but the moment I fired it up it was anything but. In fact it was maddening.

So I set a new attribute on the player object that essentially ticked down to zero. At zero the character would start to rise.
It’s a kind of pre-thrust thrust if you like.
The player touches the screen, the ticker is set, the rocket pack engages, the ticker begins the count down, a second or so later the ticker hits zero and there is enough thrust to enable the character to rise. If the player releases the touch before the ticker hits zero the ticker is forced to zero.

This worked quite well as it allowed for a reasonable amount of horizontal movement before the character started to rise up the screen.
To aid this I deliberately set horizontal motion to be very loose. In other words when the player slides his finger quickly across the screen the character zips left to right (or vice versa) at speed.

As usual when you implement this kind of thing to solve a problem you are often treated to a few surprises. One such surprise was in how nice it felt to have the character free-falling down the level and gaining speed through gravity, only to have that descent cut short in a smooth fashion thanks to the application of thrust. There is no fancy physics engine beneath all of this it is simply a case of fine tuning the numbers until I’m happy with the results.

Finally I would like to mention here that to achieve the smooth motion I deal a lot in floating point values. i.e. 1.2345 rather than 1. This affords a decent amount of granularity. But when it comes to drawing on the screen using context.drawImage() I cannot apply those floating point values to the x/y co-ordinates of the sprite. The result is a blurry mess of a sprite.
To combat this I simply round the figures down to the nearest integer with Math.round() / Math.floor() — round up and round down respectively.
All of my sprites contain an ‘angle’ attribute so rotation occurs on each sprite regardless of whether the angle is always zero.

/* g.ctx stores the 2D canvas context, o is the sprite object, the spritesheet property stores all the sprite image data */
g.ctx.save();
g.ctx.translate(Math.floor(o.x) + (Math.floor(o.w/2)),Math.floor(o.y) + (Math.floor(o.h/2)));
g.ctx.rotate(o.angle * (Math.PI / 180));
g.ctx.drawImage(o.spritesheet.image, o.frame * o.spritesheet.framewidth, o.row * o.spritesheet.frameheight, o.spritesheet.framewidth, o.spritesheet.frameheight, Math.round(-o.w/2), Math.round(-o.h/2), Math.round(o.w), Math.round(o.h));
g.ctx.restore();

(I will document my approach to spritesheeting at some point in the near future)

Sprite without rounding:

jetboy-sprite-blurred

With rounding:

jetboy-sprite

So that’s it. The game is still very much in development and I’m spending a healthy amount of time enjoying the process of designing levels. When the game is complete it will be available through the usual portals and of course Mozilla’s MarketPlace.

Crossfire – an HTML5 vertical shoot ’em up – development update

Just a quick update as work on Crossfire (previously Stargun) is moving at pace just now.

I’m very keen to use the project as an exercise in broadening the featureset of my game framework.
Currently I’m focusing on creating the kind of vertical shoot ’em up that was popular around the late 80’s and early 90’s. The sort of game that you might have played on an Atari ST or Commodore Amiga. I didn’t personally own either machine as this was a period in my life when I didn’t do much with computers – parties, playing in a rock band and girls were far more important :) – so this is very much an exercise in researching the games of the day via YouTube & VGMuseum, buying a few old magazines and firing up emulators.

It’s a huge amount of fun and the results are proving to be very exciting.
I’m still using a 2 pixel brush as a hang over from the previous game. I rather like the pixellated style of the artwork that is produced and may continue the theme through a few more games. Drawing with a bigger brush in Photoshop is a lot of fun !
I guess the irony is that the artists of the day were probably desperate to work with greater palettes and increased resolutions. They would probably look in horror at how I adoringly craft these retro-inspired spaceships and effects :)

Crossfire fighter graphic

So the features of the game are pretty established.
The in-game level editor / structure allows me to define a JSON map of the level and then iterate through based on a pre-defined delay. As the code ticks through the level row by row a new set of obstacles / bonuses / enemies / power-ups is spawned just off the top of the screen and moves slowly in to view and off down the screen.
Based on the sprite’s type and class it will then animate, glide, blink on and off, shift left and right, rotate, be destroyable or simply shoot at the player.  The combinations available to the level’s designer are huge !

I also took the decision to have the player’s fighter move instantly with the touch.
In River Raider I implemented a kind of drag effect. As you slid your finger across the screen the plane drifted in to position. A kind of drag effect. I think it worked for that game and gave you a little more to think about. But in Crossfire I wanted the movement to be instant.
It’s a mobile game so to enable this functionality and still be able to see the fighter sprite I register the first touch on the screen and move the fighter relative to subsequent touch co-ordinates. This really is the correct way to control your on-screen fighter / character. Too many times we see a virtual joypad and it really doesn’t work.

So currently I’m designing the enemy and toying with the idea of using a pre-rendered scrolling backdrop rather than just the trenchlines that I detailed in an earlier post. The game has a distinct feel and character which I think (hope) the retro shooter enthusiasts will enjoy.
It also has some cool sound effects courtesy of the Buzz JS Audio Library. Getting this to work across the board on mobile is flaky so ultimately I think the audio will be a desktop feature. But big things in mobile audio are on the horizon so watch this space.

Hoping to complete the game within a couple of weeks and push it to PlayStar (mobile only) shortly after. As always the game will be available for licencing on a non-exclusive basis.

Artwork and development for Distant Orbit

I’ve been working hard to create the visuals for Distant Orbit this last week. I know how much I enjoy looking over other developer’s workstations so I thought I’d capture mine and post them up here.

Developing the home screen

Developing the home screen and some as-yet-unused alien motherships

Designing the alien worlds

Designing the alien worlds and their inhabitants

I’m still undecided on the use of cartoon aliens. I like them but I’m not sure if it’s right for this game.

The 2nd alien world in action

The 2nd alien world in action with a half completed “monument valley” style backdrop. I use a Wacom tablet and Photoshop to create the artwork. Initially I use a broad pencil – 5px in width – and then I go dotting with a 1px pencil to create the finer details.

An early rendering of the energy tower on Tranquis

An early rendering of the energy tower on Tranquis – planet #1. I wanted each planet to have its own theme and style. This is the first planet and I wanted it to feel quite welcoming with the blue hues. The snow-capped mountains seemed to work well here and I love the completely alien tower as it rises from the horizon.

Distant Orbit screenshot

Playing with fillStyle to create some neat game effects and text

Creating games using HTML5 and the Canvas isn’t always all about using drawImage(). For the most part it is of course because we want to display our lovingly drawn sprites and environments but there are plenty of legitimate cases where we might opt for using the primitive drawing methods such as fillRect().

I use fillRect and fillText consistently in my games and have never found it to be a performance killer. At least not using the canvas dimensions 320 x 480 which I use for mobile gaming. But you should be careful. The more you ask the API to do the more of a load you place on it and at some point something has to give. Namely your framerate !
But with a bit of planning and some consideration for what you are actually presenting it can be very visually rewarding.

Distant Orbit screenshot

Distant Orbit

In Distant Orbit I’m actually using rectangles to construct the pseudo 3D tumbling landscape. It’s a very old and well-used method of creating a moving terrain.
The theory is quite simple in that the lower half of the game screen is first filled with a solid colour and the striped terrain is then a series of rectangular ‘sprites’ that scale upwards as they fall down the screen. The effect is quite nice and I save on having to draw two sets of stripes by having the underlying layer as the alternate colour.
So the underlying layer is drawn in the lighter shade and then the striped layers are drawn over the top.

I refer to the stripes as sprites since they are derived from my base sprite class. That is they inherit specific behaviours and attributes that allow me to position and present them on the screen.
It’s just that when I get to actually drawing them I’m using fillRect instead of drawImage.

Here’s an example of how you would display a rectangle.

function drawRectangle(o) // o is the incoming sprite object from which I shall derive co-ordinates and size
{
 g.ctx.fillStyle = '#bf0000';
 g.ctx.fillRect(o.x,o.y,o.w,o.h);
};

(You can see that I store the canvas context within the global namespace g)
So g.ctx.fillStyle has a hex colour value assigned to it and the following draw instruction honours it.
When I draw the rectangle I have already passed through a move() function to return the new position and dimensions of the stripe.
It is also important to note that the fillRect method uses width and height as opposed to locations in terms of scaling your shape.

Example

g.ctx.fillRect(20,20,30,30);

produces a 30×30 square with its origin at 20,20 NOT as you might expect a 10×10 square that starts at 20,20 and finishes at 30,30.

To achieve the scaling terrain effect in Distant Orbit I initialise each stripe with a height attribute of 1 pixel. As it falls down the canvas it scales until by the time it falls off the bottom it’s around 48 pixels deep.
Rather than scale the stripes by a fixed number of pixels each time (e.g. 2px) I use a modifier. This stops the stripes looking horribly uniform. By incrementing the height attribute by a modifier that itself increments with smaller numbers I get the effect that the stripe remains quite narrow for a while as if it where lost toward the horizon:

o.modifier += 0.1;
o.h += o.modifier;

So the height of the stripe would change something like this:

0.1
0.3
0.6
1.0
1.5

which gives a far nicer effect than a uniform increment such as 1, 2, 3 etc.

The beauty of this approach to drawing on screen is that it is reflected in other forms of presentation such as writing text. Instead of fillRect you just use fillText but the style is set in the exact same way.

Take a look at this code.

<!doctype html>
<html lang=en>
<head>
	<title> fillRect() </title>
	<meta charset=utf-8>
	<script>

		var g = {};
		function init()
		{
			g.ctx = document.querySelector('canvas').getContext('2d');
			fill(0,0,320,480,"#0000ff"); // Blue background
			fill(20,20,30,30,"#ffff00"); // Yellow square (10x10)
			filla(0,80,320,20,"255,255,0",0.6); // Yellow stripe with 0.6 alpha
			write("Hello, World !",160,94,"center","#ffffff",12,null,"bold");
		};

		function fill(x,y,w,h,c)
		{
			c = c ? c : "#000000";
			g.ctx.fillStyle = c;
			g.ctx.fillRect(x,y,w,h);
		};

		function filla(x,y,w,h,c,a)
		{
			c = c ? c : "0,0,0";
			a = a ? a : 0.5;
			g.ctx.fillStyle = "rgba(" + c + "," + a + ")";
			g.ctx.fillRect(x,y,w,h);
		};

		function write(t,x,y,a,c,s,f,w)
		{
			c = c ? c : "#ffffff";
			a = a ? a : "left";
			s = s ? s : 10;
			f = f ? f : "Sans-Serif";
			w = w ? w : "normal";
			g.ctx.font = w + " " + s + "px " + f;
			g.ctx.textAlign = a;
			g.ctx.fillStyle = c;
			g.ctx.fillText(t,x,y);
		};

	</script>
</head>
<body onload="init();">

	<canvas width="320" height="480"></canvas>

</body>
</html>

The basic rectangle drawing is there along with a slightly different version that allows us to provide an alpha value. This alpha range is from 0 (100% transparency, i.e. non-existant) to 1 (opaque). So for example if you provided a value of 0.5 you’d see a 50/50 blend of the background colour and your rectangle’s colour.
The key thing to remember here is that for rgba values you must specify your colours numerically.
So for White rather than #ffffff you’d specify 255,255,255.
For White with 50% alpha opacity you’d use rgba(255,255,255,0.5);

Visit this link: fillrect.html to see the above code in action.

You can see that the text also has the standard CSS attributes of alignment, font-size, font-family and font-weight. This is extremely useful when you consider that you can pull fonts from Google’s web font repository for use in your games.

By simply adding the following line to my markup I can use the “Bangers” web font family in my game.

<link href='http://fonts.googleapis.com/css?family=Bangers' rel='stylesheet' type='text/css'>

Visit this link to see the change: fillrect-newfont.html

You can see that in my code the order in which the items are drawn is important.
Starting with the blue background is important since it allows subsequent items to be drawn over the top. If the blue background were drawn last it would simply overlay everything else.
That said there is an instance where you may wish to present a solid block of colour over your content and that’s when you wish to fade your content in and/or out.
To do this we simply draw a rectangle with progressive alpha opacity as the last draw item in our draw order.

Take a look at this code for the necessary adaptations:

<!doctype html>
<html lang=en>
<head>
	<title> Fade In/Out </title>
	<meta charset=utf-8>
	<link href='http://fonts.googleapis.com/css?family=Bangers' rel='stylesheet' type='text/css'>
	<script>

		var g = {};
		function init()
		{
			g.ctx = document.querySelector('canvas').getContext('2d');
			load();
		};

		function load()
		{
			g.img = new Image();
			g.img.onload = function() {
				g.fade = 0;
				g.ticker = setTimeout("loop()", 40); 
			};
			g.img.src = "sun.jpg";
		};
		
		function loop()
		{
			clearTimeout(g.ticker);

			g.ctx.drawImage(g.img,0,0);
			filla(0,0,320,480,"0,0,0",g.fade);
			writea("Hello, World !",160,110,"center","255,255,255",32,"Bangers","normal",g.fade);
			if (g.fade < 1) { g.fade += 0.01; }

			setTimeout("loop()", 40);
		};

		function fill(x,y,w,h,c)
		{
			c = c ? c : "#000000";
			g.ctx.fillStyle = c;
			g.ctx.fillRect(x,y,w,h);
		};

		function filla(x,y,w,h,c,a)
		{
			c = c ? c : "0,0,0";
			a = a ? a : 0.5;
			g.ctx.fillStyle = "rgba(" + c + "," + a + ")";
			g.ctx.fillRect(x,y,w,h);
		};

		function write(t,x,y,a,c,s,f,w)
		{
			c = c ? c : "#ffffff";
			a = a ? a : "left";
			s = s ? s : 10;
			f = f ? "'" + f + "'" : "Sans-Serif";
			w = w ? w : "normal";
			g.ctx.font = w + " " + s + "px " + f;
			g.ctx.textAlign = a;
			g.ctx.fillStyle = c;
			g.ctx.fillText(t,x,y);
		};

		function writea(t,x,y,a,c,s,f,w,alpha)
		{
			c = c ? c : "255,255,255";
			a = a ? a : "left";
			s = s ? s : 10;
			f = f ? f : "Sans-Serif";
			w = w ? w : "normal";
			alpha = alpha ? alpha : 1;
			g.ctx.font = w + " " + s + "px " + f;
			g.ctx.textAlign = a;
			g.ctx.fillStyle = "rgba(" + c + "," + alpha + ")";
			g.ctx.fillText(t,x,y);
		};

	</script>
</head>
<body onload="init();">

	<canvas width="320" height="480"></canvas>

</body>
</html>

Very straight forward. You can see that I set a variable called fade and have it increment slowly from zero to 1. By assigning this value to the new text writing function I achieve the effect of the background fading out whilst the foreground text fades in.

Visit this link to see it in action: fadeinout.html

This was only ever intended to be a basic introduction to using shapes and text. I’d like to elaborate on it a bit in a future post and cover gradients and arcs. Anyone familiar with my games will have seen me use gradients for sky transitions in a couple of cases. I am a big fan of them as I think they offer a useful programmatic solution to something that is typically controlled by the artist.

When Distant Orbit is complete I hope to offer a bit more of an insight in to the game’s structure with regard to the drawing.

In development – River Raider – mobile HTML5 arcade game

My HTML5 take on Activision’s classic River Raid is almost complete and it’s been a huge amount of fun.

The beauty of the original game was, for me at least, in it’s slick execution. I loved the way the plane rolled left and right and accelerated the more you held the stick. I also loved some of the neat little touches like having a tank approach the bridge rather than simply destroying a bridge. There was a tremendous sense of achievement and satisfaction in timing your shot such that you took both bridge and tank out.

title graphic

As with my earlier games I never simply carbon copy the original game. I don’t see the point.
For me it’s about taking some elements, throwing a few new ones in there and crafting a cool new game from it.

My inspiration for River Raider was actually in part Capcom’s classic 1942. I had always loved the way that game played and have tried to implement a few of its cool features in to my own game.

capcom 1942

Capcom's 1942

So what does River Raider give you ? How will the game play ?

In short it’s a straight shooter where the levels are actually bumped with every bridge that you destroy.
There’s all the usual suspects: planes, boats, choppers and land to avoid (although I let the player hug the river bank – I felt that was a bit too tight on a touch screen game) and at the end of it a bridge to knock down.
Rather than one shot to destroy the bridge I decided to build the bridge in sections. So you get to destroy the bridge bit by bit. I rather liked it when I first put it in and it’s stuck.

All of the adversaries will fire back at you. The farther you progress the more frequently they will shoot.
In addition I have planes attacking from the top of the screen.
To ease you in this is initially just a single jet fighter that launches its bombs towards you as it passes.
Later you’ll see a kind of death formation of jet fighters that come at you in a number of patterns and launch missiles your way. Tricky !

River Raider

River Raider Mobile HTML5 Game

There’s really nothing too complex about implementing the attack waves since the sprites are given a default downward behaviour that is modified to either float left or right depending on a flag when they hit a certain area of the screen.
To improve the effect I perform sprite rotations depending on which direction the planes are heading.

My HTML5 game system handles this with no fuss and it adds a huge amount to the appeal of the game.

Just now I’m in a phase of balancing the firepower of the player’s fighter with the attacks that are thrown at him.
I’ve opted to have 4 attack styles just now for the fighter. A standard solitary bullet, double bullets, 4 bullets that fan out and then 6 bullets per shot that spray from the plane.
I’d like to try and add some missiles as well.

What this means of course is that the enemy are simply cannon fodder so I need to up the ante a little on their part.
Right now I’m toying with the idea of a boss stage. Or atleast a stage that involves gunning down an enemy with a different AI.

I plan on having this game completed shortly after the Easter break.

Handling grid movement

I thought it might be worth briefly sharing my approach to handling grid movement. It’s by no means finalised but just now is giving some very satisfactory results.

In every game that I make I employ a fairly basic box based method for collision detection. In reasonably fast paced arcade games where the sprites are deliberately designed to fill the box this really isn’t a problem since gamers won’t notice a couple of pixels in error. Besides I always weight the collision routine in favour of the player where relevant.

With the maze game I’ve adopted a slightly different approach to handling whether or not the player sprite is about to collide with the maze walls. ( Visit this link to read an earlier blog post on the construction of the maze walls )

The game is laid out on a 10 x 15 grid of 32 x 32 pixel blocks. The blocks are actually sprites since I want to animate them (i.e. cycle through animation frames, move in to position on level load, resize and move during the game). But unlike all other sprites in the game I won’t be using the standard collision routines.
At any given moment in the game the player will be either a) sat at a precise location that can be converted in to a grid reference or b) in transit between two grid references. This is the key to my handling of wall collision.

sprite stopped

a) Player sprite sat in "precise" grid location

sprite moving

b) Player sprite in transit between two grid locations

The graphics above should illustrate these points.
In illustration b) the player has swiped the screen to initiate movement. The game recognises the fact that the player sprite is currently not moving ( m.player.moving = false ) and is therefore cleared to attempt movement. But first we perform a test by translating the player sprite’s x,y co-ordinates in to a grid reference.

e.g. m.player.x = 128, m.player.y = 192 = the player sprite is sat at grid reference 4 , 6 (128/32, 192/32)

We can now determine which way the player wishes the sprite to travel and test the corresponding grid location to see whether a wall is sat in the way. We can perform this test against the leveldata array that stores our wall locations. You can see more on this in the blog post I linked to above.
So fairly basic so far. If a wall is in the way the move request is rejected – see below.

sprite blocked

c) Player sprite's path is blocked by a wall

Player sprite is sat at grid 4, 1. He wants to move to 5, 1. A quick lookup on the leveldata array shows us that for element 1 of the leveldata array there is an “+” sat in position 5. See below.

var leveldata = [];
leveldata[0] = [
        "+,+,+,+,+,+,+,+,+,+",
        "+, , , , ,+,+, , ,+",
        "+, , , , , , , , ,+",
        "+, ,+,+,+,+,+,+, ,+",
        "+, , , , , , , , ,+",
        "+,+,+, ,+,+, ,+,+,+",
        "+, , , , , , , , ,+",
        "+, , , , , , , , ,+",
        "+, , , , , , , , ,+",
        "+,+,+,+, , ,+,+,+,+",
        "+, , , , , , , , ,+",
        "+, , , , , , , , ,+",
        "+,+,+,+,+,+,+,+,+,+",
        "+,+,+,+,+,+,+,+,+,+",
        "+,+,+,+,+,+,+,+,+,+"
];

Where the fun begins is in the handling of new direction requests once the sprite is in motion.

A couple of things need to happen here.
First I need the player’s sprite to just keep going until a wall is hit.

In order to do this I let the sprite walk the grid only passing through the test function once its co-ordinates perfectly resolve to a grid reference. ( This my sound a bit hit and miss but I can, by initially setting the player sprite to an x and y that is divisible by 32, guarantee that this will always happen. )
My sprite walks at 8 pixel increments so moving from grid location A to grid location B takes 4 steps. This is a deliberately short timeframe between grid points. It is important for me that the player is able to register quite frequently by way of a swipe on the screen an intended next direction.

sprite new direction

d) Player sprite and indended next direction

 
This intended next direction is stored and when the player’s sprite falls perfectly in to position at the next grid reference I test this new direction instead of the actual direction. If the new direction fails the sprite just carries on on its prefered course until a) a new direction request is received or b) it hits a wall.

Of course at any point in transit the player has the freedom to “turn his sprite around”. There is nothing to stop this since the game is testing for precise locations the sprite will just fall back in to a previous grid location.

So finally a word on what happens with the other objects in the game.
Monsters will follow the same code path as the player sprite. When they hit a wall they will make a decision based on their definitions. In most cases I expect that the monsters will “hunt” for the player since this is where the challenge should be. But in some cases I will completely randomise things such that the monster will quite happily retread his footsteps. This should add enough of a mix to the game to keep the player guessing.

Other entities such as gems, powerups, bonuses, magic weapons etc will be initially placed by the leveldata[] definitions but will actually be tested for collision against the player using my standard collision routine. That way I am free to move the sprites around the maze if I wish.

So that’s it ! Nothing overly complicated at all. Of course this is all just theory written here. I’ve not posted code since the code isn’t finished. Once it is I’ll revisit some of this.
Thanks for reading.

%d bloggers like this: