I’ve got an as3 function that controls a movie clip with the keyboard:
package
{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Main_Character_Two extends MovieClip
{
var vx:int;
var vy:int;
public function Main_Character_Two()
{
init();
}
function init():void
{
//initialize variables
vx = 0;
vy = 0;
//Add event listeners
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
vx = -5;
}
else if (event.keyCode == Keyboard.RIGHT)
{
vx = 5;
}
else if (event.keyCode == Keyboard.UP)
{
vy = -5;
}
else if (event.keyCode == Keyboard.DOWN)
{
vy = 5;
}
}
function onKeyUp(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
vx = 0;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP)
{
vy = 0;
}
}
function onEnterFrame(event:Event):void
{
//Move the player
player.x += vx;
player.y += vy;
}
}
}
This works ok but the main problem is that when you press the right key (and hold it down) then press the left key, the character will move to the left but when you release the left key (with the right key still held down) the character just stops. How can I make it so the character starts moving to the right again in this situation (if Im still holding the right key after Ive released the left key)
Thanks
You could put your ‘player’ positioning code into an
Event.ENTER_FRAMEloop and useKeyboardEvent.KEY_DOWNandKeyboardEvent.KEY_UPto set booleans and position the player in the loop like:var leftIsPressed:Boolean = false; var rightIsPressed:Boolean = false; var upIsPressed:Boolean = false; var downIsPressed:Boolean = false; var speed:Number = 5; var vx:Number = 0; var vy:Number = 0; stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler); stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler); function keyDownHandler(e:KeyboardEvent):void { switch(e.keyCode) { case Keyboard.LEFT : leftIsPressed = true; break; case Keyboard.RIGHT : rightIsPressed = true; break; case Keyboard.UP : upIsPressed = true; break; case Keyboard.DOWN : downIsPressed = true; break; } } function keyUpHandler(e:KeyboardEvent):void { switch(e.keyCode) { case Keyboard.LEFT : leftIsPressed = false; break; case Keyboard.RIGHT : rightIsPressed = false; break; case Keyboard.UP : upIsPressed = false; break; case Keyboard.DOWN : downIsPressed = false; break; } } function enterFrameHandler(e:Event):void { vx = -int(leftIsPressed)*speed + int(rightIsPressed)*speed; vy = -int(upIsPressed)*speed + int(downIsPressed)*speed; player.x += vx; player.y += vy; }[EDIT] Added a more detailed example.
Of course in this case, if both left and right keys are pressed, this would result in a
0offset.