Tutorial: Simple Dynamic Perspective in AS2 and AS3


Written By MrSun at 8:00 am - Saturday, September 06th, 2008
Categories: Beginner Tutorials, Flash

This tutorial will show you how to create a simple illusion of perspective, dynamically in both ActionScript 2.0 and ActionScript 3.0. Although this technique isn’t the most advanced or realistic, it gets the job done. Let’s see it, shall we?

ActionScript 2.0

We’ll first make the effect in ActionScript 2.0. To begin, we have to create an object that we have to add the perspective to. I’m simply going to make a square that is 50x50px. Here it is:
My lil box
Next, convert it into a MovieClip. Make sure it’s registration point is set to the center. It doesn’t matter what you call it. I’m going to call mine “box”. After doing so, give your newly created MovieClip an instance name of mcBox. We can now reference it in ActionScript.

Now, simply create a new layer called “actions” and place the following code into it:

//creating a function that will run every frame
mcBox.onEnterFrame = function(){
	//scaling the box based on the y value
	mcBox._xscale = 100*(mcBox._y/Stage.height);
	mcBox._yscale = 100*(mcBox._y/Stage.height);
	
	//making the box follow the mouse
	//so we can actually show the perspective change dynamically
	mcBox._x = _xmouse;
	mcBox._y = _ymouse;
}

It’s pretty easy, right? But, if we test out the application, it isn’t as realistic as it could be. All you have to do to help with it is to add a gradient to the background, and have a horizon line at the top. Here’s the final product:

ActionScript 3.0

Now, we can make this effect in ActionScript 3.0. We’re going to start off with the same thing as we did in AS2. If you skipped that part, don’t worry I’ll sum it up for you.

  1. Make a 50x50px box
  2. Convert it into a MovieClip with registration point in center
  3. Give it an instance name of mcBox
  4. Create a new layer called actions

Now, all we have to do is add some code to the actions layer. Here it is:

mcBox.addEventListener(Event.ENTER_FRAME, moveBox);

//creating a function that will run every frame
function moveBox(event:Event):void{
	//scaling the box based on the y value
	mcBox.scaleX = mcBox.y/stage.stageHeight;
	mcBox.scaleY = mcBox.y/stage.stageHeight;
	
	//making the box follow the mouse
	//so we can actually show the perspective change dynamically
	mcBox.x = mouseX;
	mcBox.y = mouseY;
}

Pretty nifty code, eh? Well, here’s what it’ll turn out to look like (after I add a gradient background).

One Comment

Ollie:

Great tutorial just a little spelling error.
“We can no reference it in ActionScript.”
Should be
“We can *now* reference it in ActionScript.”

Keep up the good work 🙂

-Ollie


«
»