Adobe animate collision

I am making a game in adobe with AS3.I want to stop my plaza when it collides with the left barrier and does not let it through. The instance name for my box is called "drawer" and my barriers are called "left" and "right".

Here is my scene image : scene image

And here is my code for moving the window 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 very much!

+3


source to share


1 answer


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 the function fl_MoveInDirectionOfKey

+1


source







All Articles