I am making an RPG in flashpunk and would like to make it so that you can only move in 4 directions (up, down, left, and right). However when I code it when both the left and up button are pressed, for example, the player sprite moves both up and left at the same time. Any way around this?
4 Direction Movement
zachwlewis
(Zachary Lewis)
#2
In my experience, the best-feeling movement is one where the player will move in the last direction pressed. This can be accomplished most easily by using a stack and operating on Input.press()
and Input.release()
functions.
public class GameWorld extends World
{
/**
* Movement Input Stack
* Key values will be pushed to and popped from this stack as the
* player presses movement keys.
*/
protected var _miStack:Vector.<String> = new Vector.<String>();
override public function update():void
{
// Begin by checking for key presses and storing them.
if (Input.pressed(Key.UP)) { _miStack.push(Key.UP); }
if (Input.pressed(Key.DOWN)) { _miStack.push(Key.DOWN); }
if (Input.pressed(Key.LEFT)) { _miStack.push(Key.LEFT); }
if (Input.pressed(Key.RIGHT)) { _miStack.push(Key.RIGHT); }
// Next, check for key releases and remove them.
if (_miStack.indexOf(Key.UP) > -1) {
_miStack.splice(_miStack.indexOf(Key.UP), 1);
}
if (_miStack.indexOf(Key.DOWN) > -1) {
_miStack.splice(_miStack.indexOf(Key.DOWN), 1);
}
if (_miStack.indexOf(Key.LEFT) > -1) {
_miStack.splice(_miStack.indexOf(Key.LEFT), 1);
}
if (_miStack.indexOf(Key.RIGHT) > -1) {
_miStack.splice(_miStack.indexOf(Key.RIGHT), 1);
}
/*
Since values were pushed to the end of the stack and removed in place, the most
recently pressed key will be at the top of the stack. If the stack isn't empty,
move in the direction of the last item in _miStack.
*/
var direction:String = "";
if (_miStack.length > 0) { direction = _miStack[_miStack.length - 1]; }
/*
The direction of movement is now known and can be handled by either a
switch statement or a series of if statements.
*/
super.update();
}
}