Category Archives: canvas

Saving some frames by throwing a canvas at drawImage()

My next project is to be a maze game. I’d already ditched the idea of recreating a Gauntlet style romp through multiple dungeons because I wasn’t happy with the behaviour of the monsters. Getting stuck on walls and bunching up to block an open doorway was driving me mad. That’s when I started HyperGunner.

Two games later and the diversion has done me some good in that I now want to go back to the idea of a maze style game.

With all that I’ve learned in the last 2 months about controls and presentation on mobile devices I figured it ought to be a good project. The first thing to change was the screen resolution. In with 320 x 480 and out with the ridiculous 800 x 320 of the previous attempt.

I called the game Mutant Mayhem.
This is an old title for me that dates back to my days at Software Creations where a young coder and I teamed up to put 3D on a GameBoy Advance. Well, raycasting but the effect was the same. It was essentially Doom and performed beautifully. I’d created some cool weapons that the player could view as if in first person mode. I’d pixelled the hands (with twitching fingers during idle times – was very proud of that) and a whole array of monsters. I thought it was good work.
At this time we both read about how Doom’s designers had found the whole scientists over-run by lab experiments style of game a bit cliched and tired. Hence why hell came through the teleports on Mars rather than mutants running riot. But we liked the former idea and stuck with the title Mutant Mayhem. It was to be a similar game to Doom in that you run each level blasting mutants and locating keycards to escape.

Almost 10 years later I want to revisit the concept in a 2D view.
I have my level editor which I developed for the Gauntlet game and adapted it for a tighter resolution with neater graphics.

The trouble was each wall tile was around 32×32 in a 320×480 canvas. For a level with many walls the game loop was potentially performing drawImage() on each tile several hundred times per second.
Performance was atrocious.

So I threw the question to the group and found a solution.

The theory is simple.
Because I only really need to build the tile map once at the start of each level I simply create a canvas and draw the tile images to its context in a single loop.
I then pass this canvas in to the drawImage() method in the actual game loop.

Step 1: Create the new tile canvas in my init() function. (Note: I have a global namespace defined as g)

g.tileset = document.createElement("canvas");
g.tileset.setAttribute("id","tileset");
g.tileset.style.display = "none";
g.tileset.width = g.canvaswidth;
g.tileset.height = g.canvasheight;

document.getElementsByTagName("body")[0].appendChild(g.tileset);
g.tilectx = g.tileset.getContext('2d');

Notice how the canvas is not visible. Very important !

Step 2: Draw all tile images based on the level data to the canvas on level load

g.tilectx.clearRect(0, 0, g.canvaswidth, g.canvasheight);
for (var a=0;a<levels[g.level].tiles.length;a++)
{
  var o = levels[g.level].tiles[a];
  g.tilectx.drawImage(o.image,o.x,o.y);
}

You can see that all my level data is held within the levels[] array.

Step 3. Use the canvas in my main drawImage()

g.ctx.drawImage(g.tileset, 0,0);

The alternative to this would have been something like this:

for (var a=0;a<levels[g.level].tiles.length;a++)
{
  var o = levels[g.level].tiles[a];
  g.ctx.drawImage(o.image,o.x,o.y);
}

.. on every game loop. Which is a crippler !
You can see what I’ve done so far here: http://www.wilfscorner.co.uk/sandpit/mutant/

Ignore the car ;-)

Spy Hunter homage almost complete

Spy Chase screenshot

Spy Chase screenshot

Spy Chase, my Spy Hunter inspired arcade game, is motoring along and very nearly complete.

I finally got around to adding guns and missiles to the game which for me was a vital final piece of the game’s design. I think I balanced the action pretty well so that the player, with a little skill, can be the dominant force in the game.

I like to design my games based on a countering method to the obstacles and challenges.

From the outset the player faces the challenge of simply steering to remain on the road. At the head of the screen the player sees a radar. Before long it becomes apparent that the white blip is the player and the black blip is the target spy car.
Collecting flags increases the car’s speed such that steering becomes more of an issue. To avoid that becoming a breeze for the player I penalise him for hitting the road verges by a) slowing the car down and b) adding damage (reflected with a red damage bar).

This in itself is enough of a challenge to carry the game along a bit but I wanted a lot more early on.
So I added other cars to the road. Initially I intended to have the cars run the player off the road but ultimately I settled on having them as a distraction. The player can bump them from the road and earn a points bonus after each stage. It’s still a challenge just to bump them (or shoot them) from the road.

Finally I added a chopper which at set periods drops oil bombs on the road.
If the player collides with the oil his speed is reduced, the car spins and loses the missiles powerup if the player has collected it.

All in all there’s some high-speed fun to be had en route to actually capturing the spy.

Once the game is complete I’ll add some more detail to these design notes.

The game is designed with mobile devices in mind and has been tested on iPod Touch, iPhone, iPad and HTC Desire.
Any feedback from other handset owners would be gratefully recieved ;-)

You can play the latest version here: http://www.wilfscorner.co.uk/sandpit/spyhunter/

 

HyperGunner – collision detection improvements

Something that I should have paid more attention to with the development of HyperGunner was the collision between the player’s starship and the alien’s bombs. During the more intense battles it’s not uncommon to see the player trapped within a mess of bombs with very little room to move.
The problem was that the collision detection worked on the bounding boxes of both sprites. Unless the sprites contain pixels drawn to the very edges the illusion (and resulting loss of life) will be less than satisfying for the player.

Take a look at this graphic.

Collision detection

Here you can see (on the left) how I was previously performing the collision detection. Where things happen quickly and on a larger scale it’s rather more forgiving to have this style of detection. For example – the player’s laser colliding with an alien. Generally speaking players are far more forgiving when the resulting effect is in their favour !
But with a slow moving alien bomb drifting down the screen it can be highly irritating to “die” when you’re fairly sure you’ve missed it.

So I took a leaf out of my beloved manic shooters and shrank the collision box. In those games it’s fairly common to have just a single pixel in the centre of the player’s ship to collide with. But my game just isn’t that chaotic !

The net effect here is of course that you can generally be pixel perfect and watch the alien bomb pass through the outer 4 pixels of the player’s ship. But that is far more acceptable than what we had previously.

 

HyperGunner update

HyperGunner screens

I’m in the final stages of tidying up my new frantic shooter HyperGunner.
I’ve loved putting this game together and thoroughly enjoyed playing it. It’s a huge step closer to creating something in the mould of my favourite manic shooters – Ikaruga, Don Pachi, Esp RaDe et al.

I still have concerns with the collision box but essentially the game is playable.

http://www.wilfscorner.co.uk/games/hypergunner

I’m now working on streamlining the game for mobile devices. Specifically iOS and Android.

HyperGunner – not much more to do

So I thought I’d share the link.

http://www.wilfscorner.co.uk/sandpit/hypergunner/ (development version)

About 80% complete.
Some more sprites to create and a few more backdrops but essentially the core game is in place.

Feedback welcomed.

HyperGunner – new screens

HyperGunner screenshot

HyperGunner screenshot

HyperGunner screenshot

Lots of colour. Lots of action. Chaos ! I love it.

New game – old game: HyperGunner

I’ve been very busy this last few days turning Wizard Wars in to a vertical scrolling shooter.
It was very easy. Some things cropped up en route that I thought were worth a mention.

When I designed Wizard Wars I made sure that the pipeline was simple. That is, I define the images and animation specifics in the code and then I’m free to go off in to Photoshop to create some sprites. I wanted to be in a position where I could comfortably hit F5 and see my new artwork in an instant. (Chrome’s inexplicable caching aside this has been fine)

Lifting the Wizard code and turning things around a bit wasn’t so much of a challenge. I implemented some simple stars that varied in shades of grey and had them tumble down the screen at varying speeds to give that oh-so-familiar starfield depth impression. I also lifted the sprites from Invaders from Mars and had them shift across the screen whilst the player shuffled his laser cannon back and to taking shots etc etc.

Making Space Invader style games is easy. I got bored of it almost instantly.

So I shelved it and went off to play a few classic shoot-em ups in MAME.
Giga Wing, Esp RaDe, Don Pachi, Loop Master… they’re all up there in my favourite list. I played them all to death.

When I got back to my own game I realised that it was all very pedestrian and lacking in colour and depth.

So I changed the image files for most things to create richer colours.
It was whilst I was adjusting the star sprites that I realised I was doing it wrong.

All I wanted from the stars was the impression of space. I could achieve this with the simple drawing of dots / lines.
I’d draw lines and shapes on the canvas before so I changed the code and hey presto I had a starfield made up of very short lines instead of graphics. I also used context.fillStyle = “rgba(r,g,b,a)” to create some colours mathematically and with varying amounts of alpha.
Not only did I have a nice colourful starfield and some added performance I also had more control. So I played with the numbers.

I’m drawing my stars using context.fillRect(x,y,w,h).
By adjusting the width and height values I could achieve a sense of hyperspace. I also increased the amount which the stars move down the screen. This changed everything. I now realised that I had a game that would be played at pace. Even if the foreground aliens, bombs, lasers etc were moving fairly slow the background pace would make the whole thing seem pretty rapid. I loved the effect. So much so that I made hyperspace one of the mini goals of the game.

Whilst the game was in its infancy I also took the time to play with the drawing.
My initial concern was that the clearRect() method was killing performance.
So I tried a newer method: g.canvas.width = g.canvas.width;
There was no improvement.
I also went to the trouble of calculating the empty spaces left by each sprite and only re-drawing those areas on every tick. When I got the code right (it was very untidy to begin with – stray pixels here and there) it worked well but there was no real gain in frames.
The biggest boost I could find was transfering the actual drawing from using HTML Images  to primitive canvas shapes – in this case rectangles. Whereas previously I had 100 + star images cascading down the screen I now have 100+ shapes being drawn.

Google’s Chrome has easily the best performance so far. Running flat out at 250 FPS.
Firefox is the poorest at around 80 – 100 FPS flat out.
But even then the game plays very well across all browsers.

I hope to put a link up soon.

How Galaxians changed my life

Something I always wanted to write up but never really worked out the right approach for was how and why I became interested in making these simple / crude / amateurish JavaScript based games.

To get the full picture we have to go back to some time around 1980 / 81. As a young boy I used to beg, steal and borrow any coins I could get and race to the cricket club at the end of the road.
On a Saturday afternoon during the summer the club was open for business and a bunch of largely stuffy old men sat and watched the delights of leather on willow. I slipped in to the clubhouse un-noticed.
In one corner there sat a cocktail cabinet of Galaxians. (See something similar here)

If I was lucky I had 20p. Two coins. Therefore two “goes”. But generally I just had the one.

The walk to the cricket club was about 5 minutes. With every step I would be processing my previous go on the game and trying to figure out my tactics for the next one. So much so that when I sat down to play I was a combination of excited and nervous beyond belief.

I got pretty good at Galaxians but soon grew tired of the ritual of begging and walking to play the game. This was the time of the emerging home computer scene.

Zoom forward a couple of years to Christmas day and I unwrapped my new home computer – a Dragon 32.

The graphics weren’t great, the sound was pretty poor and the entire contraption felt like a big biscuit tin. But I loved it. I picked up a few books on how to program BASIC and saved up coppers to grab the occasional Dragon User magazine.
I devoured the long badly printed listings from the magazines (submitted by other amateur BASIC programmers) and frantically sought to achieve the same effects that they had produced.
I admired the professional coders but knew that I was a million miles away from them in terms of capability.
Every once in a while I would catch some machine code in Dragon User and just stare at it. How on earth could anybody understand that nonsense ?

For me it was all about the BASIC programs. It seemed so devilishly easy to accept keyboard input and produce a few audio/visual effects. Such little effort.
Before long I had some very simple games knocked up. Most were text adventures but some were little blocky Space Invaders style arcade games. (I can still remember writing code to check for collision based on pixel colour !)

A year later and I’d grown tired of the Dragon. I needed to play better games.
I was lucky. My Dad was interested in the stuff I wanted to create. I whined enough for him to cave in and get me an Atari 800XL for Christmas 1984. This time I had struck gold. Awesome graphics, awesome sound and a wealth of games, books and magazines to go at. Atari was (and is, for me at least) the definition of gaming.

I adored those days of my early teens. In the years before girls and the high jinx of college took hold I could be found beavering away in my bedroom on any number of game projects. All in Atari BASIC and all very crude. But they were mine. My ideas and my creativity at work.
I would sketch out all kinds of games in class at school. Weird detailed sketches of Manic Miner style levels and bizarre characters. (So much so that a school friend quickly nicknamed me Wilf after Wilf Lunn who at that time was well known for his mad inventions on UK television).
My friends would share their ideas. Such wild and creative ideas that were, I suppose, just rip-offs of the big home computer games of the day; Jet Set Willy, Manic Miner, Suicide Express, Ant Attack, Jet Pac (still an awesome game).

I so much wanted to create my own Galaxians. I desperately wanted to create my own Spy Hunter (my favourite arcade game of the day). What could be better than a James Bond romp through all environments in cars and boats that shot at things in their way ?

Magical times where as children we were unimpressed by fancy coding routines or other such low level excellence. It was all about what our games were going to do and of course look like. It was all about the characters, the guns, the story. Ever since those days I’ve had a love, indeed passion, for arcade games in which the sole requirement is to shoot stuff.
I think you get the gist :-)

I’ve always wanted to re-capture that passion from nearly 30 years ago. I’m not a coder. I can’t do the low level stuff. C++ or *shudder* machine code turns me to ice. I code C# in work but I’m no expert. I don’t follow technical forums. It’s generally an exercise in knocking those that don’t do it the same way that you do.

I’m a dreamer. I love nothing more than dreaming up a game scenario and putting enough code in place to go and get stuck in to crafting sprites. I love Photoshop. Just watching it load and anticipating the opening up of a new document (32 x 32) fills me with delight. I have my own palettes stored and pick one for the game based on its style. Just sitting pixelling my little characters and then dropping them in to the game to me is pure pleasure. It’s personal. In many respects I’d rather not ever show them to anyone. In many respects I also feel a bit like the Ed Wood of computer games. I have all the passion but not necessarily the technical expertise. Frankly I couldn’t care less. I’m having too much fun.

So I guess to the point of this post.
For me, even as a rapidly regressing 40 year old who should know better, it’s still all about the fun. The ideas. The “what if I make him jump and shoot as well as just jump” style ideas.
When I have to be concerned with the technicalities of making this stuff happen I get bored.

That’s why I love open web technologies. I love the fact that I can open a text editor and Photoshop and see the results with the push of a button in a web browser. I’ve waited a long time for this when I think about it.

HTML5 being adopted across the board is going to allow me to not only recapture the passion from my youth but actually push it further. A lot further. There are things that I can write now with JavaScript that I simply couldn’t do back then with BASIC. Of course there are. And that’s what is so much fun. I can create almost as quick as I can dream these ideas up. I don’t use libraries or frameworks. There’s no need. The blank canvas of a new project is too exciting. I like getting my hands dirty. (Notable exception: the SoundManager2 API)

I like to keep development times short. If a game is taking more than a month to become playable (bugs and niggles aside) then I’m getting something very wrong. I’ve most likely lost sight of the initial vision. If I can’t decide on visual styles or content then I’m definitely getting something wrong.
What excites me is when ideas just fall in to place organically.
You’d be amazed how often I create a simple sprite and just walk him around the screen with no regard for collision or other such game specific things. I walk him around, watch him move and just dream a game up around it. What would be fun ? What action would be cool to do ? – Hoth Strike was initially a helicopter game in which you fly low over a desert blasting gun turrets. The more I played with it the more I was amazed at how fast it all moved. The game needed to be a bit more frenetic.

Hopefully my point is made :-)
I love making games. I love drawing the graphics. But most of all I love dreaming up the ideas and seeing how far I can push them. You don’t have to be an expert coder to make this stuff happen. You just have to have the desire.

Lesson #1 – Frame rate / canvas / HTML5 and iPhone

Writing a simple arcade game for a handheld device (and even then to be executed through a web browser) is quite different from the luxury of writing for the desktop. Not only do you have to consider the scale and colour of everything but you have to be careful with just how much you throw around.

I no longer use DIVs and IMG files instead opting to use the Canvas element courtesy of HTML5.

IFM screenshot

Invaders from Mars - optimised for iPhone

When I first started writing with the iPhone in mind I thought I had run in to some serious canvas limitations. I was essentially doing the same thing with the same routines but somehow the approach seemed to yield a far lower frame rate. It didn’t make sense to me since iPhone is pretty powerful, right ?
I scratched my head. Could it really be that wiping the entire screen and then redrawing everything (regardless of whether it has moved) was such a drain on the device’s performance ? I certainly didn’t want to go to the trouble of detecting which sprites occupied certain regions before clearing the canvas down. Besides that would probably be an even bigger ask.

But the it dawned on me that my methods were not ideal.

I’ll try to explain.

When I populate the game with entities I essentially pick them from a pot.
During initialisation I build arrays of entities. In most cases for things like explosions I create a pot of about 50 objects. Same goes for alien bombs and player lasers. I also tend to throw around spark effects and various other niceties.
When the game loop requests such an entity it enters a loop and looks for the object that isn’t currently visible.
Where there is a lot going on on-screen this can stretch to pretty much the array length.
When it finds an object to use it simply breaks out of the loop and returns the object.

In total I was probably asking my game loop to step through an array of around 300 elements 20 – 30 times a second.
I then pass these objects in to the relevant method – draw(), move(), collision() – and have each method handle the situation in its own container.
Where the object being passed is not visible (i.e. it’s been destroyed / picked up, left the screen boundaries or hasn’t yet been used) I simply back out of the method.

if (!object.visible) return;

This works well and obviously saves a huge amount of crunching when you’re trying to perform the same actions several times a second.

So I put together a couple of tests.
In one corner I had my current and unedited game file.
In the other corner I had a new game file with the array sizes drastically reduced. A small and insignificant changes you might think !
Both files were running flat out.

I ran them both and took the diags.
Both were running in Firefox 3.6.

The first file gave me around 77 FPS.
The second (with the reduced array sizes) gave me around 90 FPS.

I’ve yet to test this on the iPhone but I would hope to see frame rates increase from the 16 – 18 FPS that I was experiencing earlier.
Something around 25 FPS ought to be acceptable for a simple Space Invader game.

I’m rather pleased to see this since the alternative was alter the game’s design.
It’s important for me to have plenty to shoot at. The first thing to go would have been the fancy sparks and screen full of entities. Never the aliens and explosions.
I also took the decision to reduce the amount of lasers that the player can launch and have on screen at any one time. It’s not ideal but will probably make for a more intense game.
Finally I dropped the alien bomb pot from 30 to 4. Only 4 alien bombs on screen at once !

To counter this I ditched the idea of an energy bar that gets depleted with every hit from an alien bomb.
Instead I went for the classic one hit and you’re out a la Space Invaders / Galaga etc.
Again this tends towards a more intense experience.

So all in all a worthwhile exercise. It sets me up a bit more for crafting such games for mobile devices. Something I needed to do if I’m to maintain the amount of games I’m hoping to produce each month.

new iPhone game – Wizard Wars

During the crafting of my Gauntlet-esque game I lost some motivation. The issue of rotation vs collision took its toll. I needed something to just jump in to so that I could get a game completed. It’s hugely frustrating for me not to finish something once I set my mind to it.

So I took a look at the iPhone. I’d looked at Objective-C and scratched my head enough to ask the question “Can I make games for the iPhone without Objective-C and Cocoa ?”. So much infact that I punched exactly that in to Google.
Incredibly a book available on Amazon called Building iPhone Apps with HTML, CSS, and JavaScript: Making App Store Apps Without Objective-C or Cocoa was returned. I wasted no time buying it.
When it came I devoured it. It’s not a big book but gives you every bit of markup and code that you need to present a game in an iPhone / iPod Touch.

Safari Mobile is sturdy and executes at a good pace. I tested the game using desktop Safari on a PC and my wife’s iPod Touch. Although the framerate drops on the actual device it’s certainly good enough to present a good game.

Wizard Wars game for iPhone (in development)

It’s not quite finished but you can still see it here: www.wilfscorner.co.uk/sandpit/iphone

I didn’t waste too much time on game design issues. I pretty much knew from the outset that I wanted a colourful game with a wizard battling another evil wizard in a fixed arena. I wanted the game to feel nice. When you touch the screen the character moves to that point. I also reflected the target position using a simple red blob sprite that fades over time. The effect when you drag the wizard is quite pleasing if totally accidental.

As a GameBoy artist I learnt very quickly that colour is vital. Bright, vibrant colours can make a simple game experience really enjoyable. So I set out to create bright colourful sprites.

The easiest way to achieve this was to wash out the backdrop. So I set the entire game on a patchwork stone floor that is actually quite dark. I then crafted a bunch of sprites using the opposite end of the spectrum. The effect is very nice and rather rewarding for an artist / game designer.

When I first set out to create the game I was concerned about frame rate. I needn’t have been. Safari Mobile handles things nicely. So much so that I was able to spawn my trademark spark flashes all over the place. The process of picking gems and stars up is dull if you don’t visually reward the player. The 8 way explosion of sparks is perfect feedback.
I also invested some time making this bob and bounce a little. So stars, gems and bonuses don’t just appear they drop a short height and bounce in to position. Very little code used for a thoroughly worthwhile effect.

I hope to blog a bit more about the game’s development once it’s complete. Just now I’m wrapping up the sound issues (AUDIO tag) and tightening up the code and resource files. I’m desperate to keep the whole project under 300k.

Have a look at the game. You can play it on a PC using the mouse to click the arena or the keyboard arrow keys to move the wizard.
Let me know what you think.