At the current stage of development, this little app has an "inner boundary" where the player object is restricted. Attempting to move beyond, scrolls the background... you know the drill.
However, if two keys are pressed (Down & Right, for example) the boundary is ignored, but player snaps back into position after letting go of the keys. What am I missing?
Thanks in advance to anyone that has a second to look at it!
Code below, and code in action here
Code: Select all
import flash.events.Event;
import flash.events.KeyboardEvent;
var playerHalfHeight:uint = player.height/2;
var playerHalfWidth:uint = player.width/2;
var stageHalfHeight:uint = stage.stageHeight/2;
var stageHalfWidth:uint = stage.stageWidth/2;
var backgroundHalfHeight:uint = background.height/2;
var backgroundHalfWidth:uint = background.width/2;
var vx:Number = 0;
var vy:Number = 0;
var playerInnerRightBoundary:uint = stageHalfWidth + (stageHalfWidth/2);
var playerInnerLeftBoundary:uint = stageHalfWidth - (stageHalfWidth/2);
var playerInnerTopBoundary:uint = stageHalfHeight - (stageHalfHeight/2);
var playerInnerBottomBoundary:uint = stageHalfHeight + (stageHalfHeight/2);
stage.addEventListener(Event.ENTER_FRAME,eachFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyHandlerDown);
stage.addEventListener(KeyboardEvent.KEY_UP,keyHandlerUp);
function keyHandlerDown (event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
vx = -5;
}
if (event.keyCode == Keyboard.RIGHT)
{
vx = 5;
}
if (event.keyCode == Keyboard.UP)
{
vy = -5;
}
if (event.keyCode == Keyboard.DOWN)
{
vy = 5;
}
}
function keyHandlerUp (event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
vx = 0;
}
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
vy = 0;
}
}
function eachFrame (event:Event):void
{
player.rotation += 1;
player.x += vx;
player.y += vy;
if (player.x > playerInnerRightBoundary-playerHalfWidth)
{
player.x = playerInnerRightBoundary-playerHalfWidth;
background.x += -vx;
}
else if (player.x < playerInnerLeftBoundary+playerHalfWidth)
{
player.x = playerInnerLeftBoundary + playerHalfWidth;
background.x += -vx;
}
else if (player.y < playerInnerTopBoundary + playerHalfHeight)
{
player.y = playerInnerTopBoundary + playerHalfHeight;
background.y += -vy;
}
else if (player.y > playerInnerBottomBoundary-playerHalfHeight)
{
player.y = playerInnerBottomBoundary - playerHalfHeight;
background.y += -vy;
}
if (background.x + backgroundHalfWidth < stage.stageWidth)
{
background.x = stage.stageWidth - backgroundHalfWidth;
}
else if (background.x - backgroundHalfWidth > 0)
{
background.x = 0 + backgroundHalfWidth;
}
else if (background.y - backgroundHalfHeight > 0)
{
background.y = 0 + backgroundHalfHeight;
}
else if (background.y + backgroundHalfHeight < stage.stageHeight)
{
background.y = stage.stageHeight - backgroundHalfHeight;
}
}