Jolie Rouge


all ur parentheses Я belong to me


How To Flash CS5: Keyboard Navigation Action Script 3 KeyboardEvents

Well,

I was watching an interesting little tutorial on keyboard navigation with AS3. Now, the guy’s tutorial was actually really good, however, it wasn’t really what I would call AS3. It was very on target for what it was doing, but didn’t leave much room for expansion in my opinion. So I decided to try my hand at changing it up a littler bit.

Here is the code:

This is put on the main timeline, in the first frame on an actions layer. That is, you just create a new layer, and name it actions, it’s just a convention.

import flash.events.KeyboardEvent;
import flash.events.Event;

var currentKeyDown:uint = 0;
var Keys:Object = {up: 38, down: 40, left: 37, right: 39,r:82, shift: 16, ctrl: 17, z:90, x:88};
var CurrentKeysDown:Object = {up: false, down: false, left: false, right: false, shift: false, ctrl:false};

stage.addEventListener(KeyboardEvent.KEY_DOWN,setCurrentKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,clearCurrentKeyDown);
setTimeout(updateCanvas,100);

function setCurrentKeyDown(event:KeyboardEvent):void {
	trace(event.keyCode);
	for (var key:String in Keys) {
		if (Keys[key] == event.keyCode) {
			CurrentKeysDown[key] = true;
		}
	}
}
function clearCurrentKeyDown(event:KeyboardEvent):void {
	for (var key:String in Keys) {
		if (Keys[key] == event.keyCode) {
			CurrentKeysDown[key] = false;
		}
	}
}
function moveEntity(entity:MovieClip):void {
	currentKeyDown = 0;
	var x:Number = 0;
	var y:Number = 0;
	for (var key:String in Keys) {
		if (CurrentKeysDown[key]) {
			currentKeyDown = Keys[key];
		}
		switch (currentKeyDown) {
			case Keys.shift:
				entity.speed += entity.speed * .05;
			break;
			case Keys.ctrl:
				entity.speed -= entity.speed * .05;
			break;
			case Keys.z:
				entity.rotationSpeed += entity.speed * .06;
			break;
			case Keys.x:
				entity.rotationSpeed -= entity.speed * .06;
			break;
			case Keys.r:
				entity.x = 200;
				entity.y = 200;
				break;
			case Keys.left:
				entity.rotation = entity.rotation - entity.rotationSpeed;
			break;
			case Keys.right:
				entity.rotation = entity.rotation + entity.rotationSpeed;
			break;
			case Keys.up:
				if (entity.rotation <= -90) {
					x = -1 * (entity.speed * (entity.rotation + 180)/100);
					y = -1 * (entity.speed * (entity.rotation + 90)/100);
				} else if (entity.rotation <= 0) {
					x = entity.speed * entity.rotation / 100;
					y = -1 * (entity.speed * (entity.rotation + 90) / 100);
				} else if (entity.rotation <= 90) {
					x = entity.speed * entity.rotation / 100;
					y = entity.speed * (entity.rotation - 90) / 100;
				} else if (entity.rotation <= 180) {
					x = entity.speed * (180 - entity.rotation) / 100;
					y = entity.speed * (entity.rotation - 90) / 100;
				}
				entity.x += x;
				entity.y += y;
			break;
			case Keys.down:

				if (entity.rotation <= -90) {
					x = entity.speed * (entity.rotation + 180) / 100;
					y = entity.speed * (entity.rotation + 90) / 100;
				} else if (entity.rotation <= 0) {
					x = -1 * (entity.speed * entity.rotation / 100);
					y = entity.speed * (entity.rotation + 90) / 100;
				} else if (entity.rotation <= 90) {
					x = -1 * ( entity.speed * entity.rotation / 100 );
					y = -1 * ( entity.speed * (entity.rotation - 90) / 100);
				} else if (entity.rotation <= 180) {
					x = -1 * ( entity.speed * (180 - entity.rotation) / 100 );
					y = -1 * ( entity.speed * (entity.rotation - 90) / 100 );
				}
				entity.x += x;
				entity.y += y;
			break;
		}
	}

}
function updateCanvas():void {
	moveEntity(Object(this).Ship);
	Object(this).SpeedLabel.text = "Speed: " + Object(this).Ship.speed;
	Object(this).RotationSpeedLabel.text = "Rotation: " + Object(this).Ship.rotationSpeed;
	setTimeout(updateCanvas,25);
}

On thing to note here is, I am not using onEnterFrame. There are a couple of reasons for this, anti-cheating, i.e. it's time based, not frame based, so slowing down the frames, won't do anything. Also,
on different computers, the thing seemed to execute faster with onEnterFrame, this way, it's a time interval using setTimeout, so it should be a little more consistent.

Then, I created a small triangle, converted it to a movieclip with F8, double clicked it, inserted a new layer, named that one actions, and put this code in the first frame.

var baseSpeed:Number = 1;
var baseRotationSpeed:Number = 1;
var speed:Number = baseSpeed;
var rotationSpeed:Number = baseRotationSpeed;

Most of this should be self explanitory. A few things that may be weird are the calculations for the up keying. Basically, we have a rotation value from 0 -> 180, and from -180 -> 0, so we need to behave differently based on which direction we are facing. Negative numbers need to be multiplied by -1 to get rid of the negative sign. In some cases, we want to diminish the x or y movement, so we add or subtract to/from 180 degrees and sometimes 90 degrees. For instance, when we are between -90 and -180, we add 180 to the x calculation, which means, the closer we are to -180 rotation, the less we will move along the x axis etc. Same for positive 180.

You will notice that, for the most part, pushing 2 arrow keys at once get you different behavior, that is, you'll loop around. Also, you can use shift/ctrl for +/- speed, and z/x +/- rotation.

pushing r, resets the ship in case you get lost.

Hope you enjoy!
/Jason

  • ozkan

    i have maze , and im trying to rotate the player when i try with ur codes i keep getting error.. can you help?

  • Tepu92

    Can you import that Flash project on the page.
    I’m trying to figure out, how i can use the code on my flash animation.

    I copy/Paste the codes and follow the guide, but it’s not working.
    TNX!

    • Anonymous

      Hey,

      Sorry mate, it’s been awhile since I worked in flash, I don’t have it currently installed, or the original code for this thing.

      Things might have changed since I did this bust usually you place this code either in a file and import it in the first frame of the animation, or actually just put the code in the actions frame that you will have to make…

      As much as I would like to get back to AS3 and do something with Flash, I just don’t get much work in that field, I spend more of my time with backend server programming these days.

      I hope you manage to figure it out though.

      Cheers

  • Noel

    Hello there
    Im trying to get the string value from keyCode(Without ‘if-else’ ing the individual keys my self) I know that you can do this with charCode but can you do the following?

    function OnKeyDown( keyboardEvent:KeyboardEvent ):void
    {
    var str:String = MagicFunction( keyboardEvent.keyCode );
    //if keyCode == 13
    // str == “Return”
    // Does AS3 Provide MagicFunction()?
    }

    THANKS 😀
    Keep up the good work!

  • Awesome and genius! Thank you very much for this post. Your blog is excellent, by the way.