Friday, 10 October 2008

Switches and Key Listeners for Game Controls

Well I just can't help fiddling around with code to see what I can do. I began toying with making some kind of game where you control a craft of some kind and must avoid the bad things and pick-up the good things.

Rather than dive straight into graphics I followed the best practice and began making the code work first. What follows is the simple beginnings of a game control script that uses a key listener object to check what key the player is using. Then, instead of using if else as I might usually be tempted to do I decided to use a switch to check which key is being pressed and change the direction of acceleration accordingly. For this to work for you, all you need to do it dump a movieclip onto the stage with the instance name "ship_MC", then copy the following code into your first key frame:

/*Up, down, left and right keys control direction. Space is the emergency brake.*/

/*Set initial values for direction and speed, and the rate of acceleration */
xspeed = 0;
yspeed = 0;
accelerate = 1;

/*Create the key listerner object*/
var myControlKeyListener:Object = new Object();

/*Set up a conditional response to the key press that changes the value of xspeed and yspeed depending on which key is being pressed and for how long.*/
myControlKeyListener.onKeyDown = function() {
switch (Key.getCode()) {
case Key.SPACE :
xspeed = 0;
yspeed = 0;
case Key.LEFT :
xspeed -= accelerate;
case Key.UP :
yspeed -= accelerate;
case Key.RIGHT :
xspeed += accelerate;
case Key.DOWN :
yspeed += accelerate;
/*Add the key listener*/

/*Animate the direction and velocity of the ship_MC movie clip according to the value of xspeed and yspeed */
onEnterFrame = function () {
this.ship_MC._x += xspeed;
this.ship_MC._y += yspeed;

The comments between the /* */ in the code above explain how it works. If you have not used switch before, and tend to stick to if else you will find in some cases that switch is much easier to work out the logic for and takes less typing.

Demo SWF