Saturday, 1 August 2009

Dynamically centre object in Actionscript 3

In this tutorial you will learn how to dynamically centre an object on the stage using Actionscript 3.0 code. This avoids you manually locating the centre of the stage which can save you time. I will demonstrate the centring of an object using a basic rectangle shape.


Dynamically centre object in Actionscript 3

Step 1

Open a Flash AS3 file.
Select the rectangle tool and drag a rectangle shape on the stage like below:




Step 2

Convert your shape into symbol by pressing F8. Give your symbol an appropriate name, check movie clip and click ok.

Now give your movie clip the instance name ‘rectangle_mc’ as shown below:




Step 3

Insert a new layer on the timeline called “Actions”. Select the first frame and hit F9 to open up the actions panel, and enter the following code:

rectangle_mc.x=rectangle_mc.stage.stageWidth/2-rectangle_mc.width/2;
rectangle_mc.y=rectangle_mc.stage.stageHeight/2-rectangle_mc.height/2;


The code above can get quite irritating if you need to centre multiple objects. Below is the function for centring an object. This allows you to call a function rather than writing out lots of code:

function alignCentre(obj:DisplayObject):void {
obj.x=obj.stage.stageWidth/2-obj.width/2;
obj.y=obj.stage.stageHeight/2-obj.height/2;
}

Step 4

Test your object centring Ctrl + Enter. You should notice your object in the centre of the stage.



You should now be able to centre an object using Actionscript 3.0 code.

2 comments:

Bram 2 March 2010 at 07:21  

So how do I invoke the function? Coz it wont centered when I run it..

iliketo 2 March 2010 at 10:41  

This is very basic.

alignCentre(yourInstanceName);

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP