Moving stuff with arrow keys and WASD.

23 Jul

I made a little drawing called ‘Ship’. The following code lets you move ‘Ship’ left and right using the arrow keys and the keys ‘A’ and ‘D’.

package {
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	import flash.events.Event;
	import flash.ui.Keyboard;
	public class Engine extends MovieClip {
		var ourShip:Ship = new Ship();
		var speed:Number = 4;
		var leftPressed:Boolean = false;
		var rightPressed:Boolean = false;
		public function Engine():void{
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		public function init(e:Event) {
			ourShip.x = stage.stageWidth / 2;
			ourShip.y = stage.stageHeight - 50;
			stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeys);
			stage.addEventListener(KeyboardEvent.KEY_UP, removal);
			stage.addChild(ourShip);
			addEventListener(Event.ENTER_FRAME, EnteringFrame);
			removeEventListener(Event.ADDED_TO_STAGE, init);
		}
		public function checkKeys(e:KeyboardEvent):void {
			if((e.keyCode == 37) || (e.keyCode == 65)){
				leftPressed = true;
			}
			if((e.keyCode == 39) || (e.keyCode == 68)){
				rightPressed = true;
			}
		}
		public function EnteringFrame(e:Event) {
			if (leftPressed && ourShip.x > 20){
				ourShip.x -= speed;
			}
			if (rightPressed && ourShip.x < 530){
				ourShip.x += speed;
			}
		}
		public function removal(e:KeyboardEvent):void {
			if((e.keyCode == 37) || (e.keyCode == 65)){
				leftPressed = false;
			}
			if((e.keyCode == 39) || (e.keyCode == 68)){
				rightPressed = false;
			}
		}
	}
}

Some credit to ‘BraydenBlack’ and ‘iBringHam’ from GDR for tweaking this a little bit. πŸ˜›

Advertisements

One Response to “Moving stuff with arrow keys and WASD.”

  1. Grant Ley August 8, 2011 at 11:45 pm #

    Very helpful! πŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: