Actionscript 3: Using modulos to wrap a moving movieclip

A clean way to wrap a movieclip wrapping around the stage is to use modulos

var widthOfStage:Number = stage.stageWidth;
var velocity:uint = 1;
myClip.x = (myClip.x + velocity) % widthOfStage;

That part is easy. The difficult part is handling moving left when you encounter negative number. The solution to that is to add the original width back in to keep it positive.

var velocity:uint = -1;
myClip.x = widthOfStage + ((myClip.x  + velocity) % widthOfStage);

A problem you might occur is if you try to move back right, your clip might jump. So to keep both left and right movement synced modify the original right movement to:

var velocity:uint = 1;
myClip.x = widthOfStage + ((myClip.x  + velocity) % widthOfStage);

[ad#Google Adsense]

Author: mark

Creative technologist

Leave a Reply

Your email address will not be published. Required fields are marked *