2013-08-11

Canvas Simple Game

Intro

Another post in the "canvas drawing series". You can look up the basics of drawing etc. in the previous posts:

  1. Canvas Crossroad
  2. Canvas Balloons
  3. Canvas Bus
  4. Canvas Trains
  5. Canvas, circular motions and networks
  6. Canvas Wipers
  7. DIY Canvas Fountain
  8. Canvas Random Spherical Effects
  9. Canvas Ant Colony Optimization
  10. Canvas Space Battle

Canvas Simple Game

I hope I'll develop some kind of "serious" game in the future, but as always the first steps are pretty modest. The Canvas Simple Game is sort of a testing playground for a Shoot 'Em Up Game type. Also, @loktar00 had an idea about growing this example to "online shmup creator". Most of the techniques used in this example are described in the previous posts. So I won't cover the basics as much. The stuff I researched the most for this example is javascript keyboard event handling. So I'll concentrate on that.

Keyboard events javascript style

Since the games usually require more of the keys pressed at the same time I've developed a simple example. Every key has it's state stored in an associative array. The keydown and keyup events can have multiple keys pressed at once, so on every key up or down the key state is changed:

  var activeKeys = [];

  function setKeysTo(e, state) {

   if(e.keyCode == 37) {
     activeKeys['left'] = state;
   } else if(e.keyCode == 39) {
     activeKeys['right'] = state;
   }  else if(e.keyCode == 38) {
     activeKeys['up'] = state;
   } else if(e.keyCode == 40) {
     activeKeys['down'] = state;
   } else if (e.keyCode == 32) {
     activeKeys['shoot'] = state;
   }

   return false;
  }

  document.onkeydown = function(e) {
   return setKeysTo(e, true);
  };

  document.onkeyup = function(e) {
   return setKeysTo(e, false);
  };

Now the application logic can check for key combinations and update stuff in the animation loop. The displayed code might be a bit redundant but it's down to the point. Perhaps this blog entry name could be javascript multiple key events handling :)

And here's my example on:
Codepen

No comments: