I am making a game in adobe animate with AS3.I want to stop my square when it collides with the left barrier and not let it go through.The instance name of my box is called 'box' and my barriers are called 'left' and 'right'.
Here is an image of my stage:image of stage
And here is my code for moving the box so far:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
box.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (leftPressed)
{
box.x -= 5;
}
if (rightPressed)
{
box.x += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
}
}
Thank you so very very much!
You need something like
if (box.hitTestObject(left)) box.x = left.x + left.width;
if (box.hitTestObject(right)) box.x = right.x - box.width;
added to the end of fl_MoveInDirectionOfKeyfunction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With