Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adobe animate collision

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!

like image 755
Hamza Avatar asked Jan 21 '26 03:01

Hamza


1 Answers

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

like image 72
Oleg Knaus Avatar answered Jan 23 '26 19:01

Oleg Knaus