Sunday, 2 November 2008

Limit movements on the stage

This flash tutorial will teach you how to limit the keyboard movements of an object on the stage. This means you can use the keyboard controls to move your movie clip instance on the stage, but you will not be able to go over the edges of the stage. To drag an object around the stage, checkout the draggble object tutorial. I have used an actionscript 2.0 file for this tutorial and a free stock image of a sheep which is available at:

Limit movement on the stage

Step 1

Open a new Flash document.
Import the image you want to limit the movements of on the stage by selecting File > Import > Import to Stage then choose your image and click open
If you wish to create your own object, you can do so at this point.

Step 2

Using the selection tool (V) select your object and convert it into a symbol by pressing F8. Give your symbol an appropriate name, check movie clip and click ok.

Give your movie clip an instance name. eg sheep_mc

Step 3

On the timeline right click on the first frame and select Actions and enter the following code. The movement of the object is same code from the key controls tutorials. This moves the object around the stage, but there is addition code which limits the object to the edges of the stage.

var speed:Number = 5;
_root.onEnterFrame = function() {

if (Key.isDown(Key.RIGHT) && (sheep_mc._x < (Stage.width-sheep_mc._width/2))) {
sheep_mc._x += speed;
else if (Key.isDown(Key.LEFT) && (sheep_mc._x > (0+sheep_mc._width/2))) {
sheep_mc._x -= speed;

if (Key.isDown(Key.UP) && (sheep_mc._y > (0+sheep_mc._height/2))) {
sheep_mc._y -= speed;
else if (Key.isDown(Key.DOWN) && (sheep_mc._y < (Stage.height-sheep_mc._height/2))) {
sheep_mc._y += speed; }

***Changing the variable number speed will increase/decrease the speed of the object movement.

he onEnterFrame event handler evaluates the conditional statements. Every time the statement is evaluated the 'sheep_mc' movie clip instance is moved to the relative position, but cannot go over edges of the stage.

Step 4

Test your movie clip by selecting Ctrl + enter. Use the left, right, up and down arrow keys to control the movement of your object, but notice you can’t go over the edge of the stage.

You should now have limited movement controls. Feel free to contact me for any questions or comments.


  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP