Tuesday, 19 January 2010

Screen wrapping in AS3

I previously created a post called limit stage boundaries in AS3 where the object was limited to the edges of the stage boundaries. In this tutorial I will provide code for screen wrapping which is when an object disappears at one side of the screen to reappear at the opposite side. This will give the illusion of a never ending loop. You will need to have completed the key control in AS3 tutorial as code will be added to this tutorial.


Screen wrapping in AS3

Step 1

Open up the key control AS3 tutorial.


Step 2

On the timeline select Actions layer then open up the Action panel (F9) and enter the following code.

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

//2.
if (object.x - objectHalfWidth>stage.stageWidth) {
object.x=0-objectHalfWidth;
}
else if (object.x + objectHalfWidth <0) {
object.x=stage.stageWidth+objectHalfWidth;
}

//3.
if (object.y + objectHalfHeight<0) {
object.y=stage.stageHeight+objectHalfHeight;
}
else if (object.y - objectHalfHeight > stage.stageHeight) {
object.y=0-objectHalfHeight;
}
}

As you can see the code is similar to the limit stage boundaries in AS3 code as the values and reversed.

1. This creates two local variables called objectHalfWidth and objectHalfHeight which stores half of the objects width and height.
2. If the object moves over the width of the stage then the object will appear at the opposite end by setting the values and the stage edges.
3. If the object moves over the height of the stage then the object will appear at the opposite end by setting the values and the stage edges.


Step 3

Add the ScreenWrapping() function inside the moveObject() function to enable the screen wrapping of the object.
ScreenWrapping(lemon_mc);

Step 4

Test your movie clip Ctrl + Enter. Now move the object using the mouse and you should see the object appear at the opposite side of the screen.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP