Search code examples
actionscript-3flashflash-cs6

How to stop a movable object (which moves via the arrow keys) from going off the stage in Adobe Flash Professional CS6 Action Script 3.0


Hey I'm currently creating a game in Adobe Flash Professional CS6. I have a character, with an instance name of "alien". So far, I've only been able to code my game so that the alien can't go off the top or left sides of the stage. I can't figure out how to code it so that the alien can't go off the bottom or right sides of the stage. The coding I have is as follows:

if((alien.x) < (alien.width/2)){
      alien.x += 10;
}
if((alien.y) < (alien.width/2)){
      alien.y += 10;
}

Thank you for your time.


Solution

  • Use stage.stageWidth and stage.stageHeight values to determine the size of the stage area. It is not mandatory to use Rectangle, but I like how self-explanatory it is.

    import flash.geom.Rectangle;
    
    // new Rectangle(left, top, width, height)
    var aBounds:Rectangle = new Rectangle(
        alien.width / 2,
        alien.height / 2,
        stage.stageWidth - alien.width,
        stage.stageHeight - alien.height
    );
    
    if (alien.y < aBounds.top) alien.y = aBounds.top;
    if (alien.x < aBounds.left) alien.x = aBounds.left;
    if (alien.x > aBounds.right) alien.x = aBounds.right;
    if (alien.y > aBounds.bottom) alien.y = aBounds.bottom;