Sunday, 20 December 2009

Limit stage boundaries in AS3

I previously wrote a post called limit movements on the stage in Actionscript 2 where an object was limited to the edges of the stage boundaries. In this tutorial I will provide the code for the Actionscript 3 version. Before attempting this tutorial make sure you have completed the Key controls in AS3 as code will be added to this tutorial.

Limit stage boundaries in AS3

Step 1

Open up the Keyboard control AS3 tutorial.

Step 2

On the timeline select the Actions layer and then open up the Actions panel and enter the following code:

function limitStageBorder(object:MovieClip) {
var objectHalfWidth:uint=object.width/2;
var objectHalfHeight:uint=object.height/2;

if (object.x+objectHalfWidth>stage.stageWidth) {
else if (object.x - objectHalfWidth <0) {

if (object.y-objectHalfHeight<0) {
else if (object.y + objectHalfHeight > stage.stageHeight) {

1.This creates two local variables which store half the objects width and height.
2.If the object moves over the stage width then the objects get pushed back by adding or subtracting the height/width of the object.
3.If the object moves over the stage height then the objects get pushed back by adding or subtracting the height/width of the object.

Step 3

You now need to add the limitStageBorder() function to enable the limiting of the stage boundaries. Place the following line of code inside moveObect() function.

Step 4

Test your movie clip Ctrl + Enter. You should now notice the object cannot move outside of the stage area.


Anonymous 22 September 2012 at 15:23  

I'd like to suggest an alternative method. As opposed to checking if the position is lower than the min and greater than the max, you can combine them in a quadratic function.
If x * (x - screenWidth) > 0, this point is located off the screen. Now take into account the width of the object.
If (x - width) * ((x - width) - screenWidth) > 0, the object will be off the screen.
It doesn't decrease the processing time that much but it's a more mathematically precise solution to the problem.

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP