Managing bounds in Actionscript 3.0

Protecting an object from going out of a certain x value. Use “D” on the keyboard to move the ship right, and “A” to move left.

Application Source

This is a continuation off from my post Keyboard Management for games in Actionscript 3 where I talk about managing multiple keys being held down at once, and how to continue executing the first keydown after the second keyUp has been done…

This blog post doesn’t scratch any surfaces as far as physics goes, but talks about some basics, like bounds… say you have an object that you apply gravity to, and when you insert the object into the stage you expect it to fall to the bottom, and stop at the bottom (pretending that the bottom is the floor) you expect the object to stop.

This post is about how to stop an object from going outside those bounds… it’s probably not easier than you thought, it usually involves math of some sort, and width and heights and comparing them…

To make things simple lets talk about a “ship” and a ship is based on a sprite, so it has a width,height,x,y and so forth…

Basic code with no bounds checking

ship.x = 350;


ship.x += 5;


Basic code WITH bounds checking

ship.x = 350;



//you have to find the farthest right the ship can go without going out

//in order to do so, you need to grab whatever it is that you want to use for bounds,

//whether it be a border rectangle or something, in this example we are using the stage,

//but in the code, I have a border class that I use

var br:Number = stage.stageWidth – ship.width;

if(ship.x >= br)

ship.x += 5;


You have to test (usually on enterFrame, unless you have a timer running your animation for more smooth results) the x and y of the object, your moving… in our case we are only using the x value to test, but you can do the same thing with the y axis, based on the stage.stageHeight – ship.height.

1 comment on this post.
  1. Changing a sprites rotation point | Axelology:

    […] side will be overlapping the boundary. So what you need to do now, is take a look at my last post Manager bounds in Actionscript 3.0 and use the code, and adjust it accordingly for the new […]

Leave a comment