Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Moving Sprite with arrow keys, simultaneous directions

Status
Not open for further replies.

maguskrool

Technical User
Dec 11, 2006
77
PT
Hi everyone.

I'm trying to create a small arcade style game, you control a small ship, shoot at incoming targets, try to dogde their shots, etc. I'm working on the ship's movement right now, using the arrow keys to control it. Getting it to move one direction at a time is easy, but sometimes I need to move it diagonally, otherwise I think gameplay will suffer considerably.

I have tried several things but I never seem to be able to tell Flash that two keys are being pressed simultaneously. Can anyone tell me how I might achieve this?

Thank you.

 
Tricky, but can be done:
Code:
//AS3
var up:Boolean, down:Boolean, right:Boolean, left:Boolean;

function onKeyboardDown(e:KeyboardEvent):void {
	switch (e.keyCode) {
		case Keyboard.UP :
			up = true;
			break;
		case Keyboard.DOWN :
			down = true;
			break;
		case Keyboard.LEFT :
			left = true;
			break;
		case Keyboard.RIGHT :
			right = true;
			break;
	}
}

function onKeyboardUp(e:KeyboardEvent):void {
	switch (e.keyCode) {
		case Keyboard.UP :
			up = false;
			break;
		case Keyboard.DOWN :
			down = false;
			break;
		case Keyboard.LEFT :
			left = false;
			break;
		case Keyboard.RIGHT :
			right = false;
			break;
	}
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyboardUp);

function onEnterFrameStage(e:Event):void {
	if (up) {
		ship.y--;
	}
	if (down) {
		ship.y++;
	}
	if (left) {
		ship.x--;
	}
	if (right) {
		ship.x++;
	}
}

stage.addEventListener(Event.ENTER_FRAME, onEnterFrameStage);

Kenneth Kawamoto
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top