Shake your MovieClip

[kml_flashembed publishmethod=”static” fversion=”8.0.0″ movie=”http://johnbarrett.net/wp-content/uploads/2013/03/shake.swf” width=”400″ height=”300″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]A friends had ask me how did I shake a MovieClip. I told him I would show me.

First step make a MovieClip, mine is an orange square, with a instance name of mcOrangeBox

Then open the actions panel

import flash.display.MovieClip;
import flash.geom.Point;

function shake(mc:MovieClip, frames:int = 10, maxShakeAmount:int = 30) : void {
    if (!mc._shakeTime || mc._shakeTime <= 0) {
        mc.startPosition = new Point(mc.x, mc.y);
        mc._shakeTime = frames;
		mc._maxShakeAmount = maxShakeAmount;
        mc.addEventListener(Event.ENTER_FRAME, handleShakeEnterFrame);
    }
    else {
        mc.startPosition = new Point(mc.x, mc.y);
        mc._shakeTime += frames;
		mc._maxShakeAmount = maxShakeAmount;
    }
}

function handleShakeEnterFrame(event:Event):void {
    var mc:MovieClip = MovieClip(event.currentTarget);
	var shakeAmount:Number = Math.min(mc._maxShakeAmount, mc._shakeTime);
    mc.x = mc.startPosition.x + (-shakeAmount / 2 + Math.random() * shakeAmount);
    mc.y = mc.startPosition.y + (-shakeAmount / 2 + Math.random() * shakeAmount);

    mc._shakeTime--;

    if (mc._shakeTime <= 0) {
        mc._shakeTime = 0;
        mc.removeEventListener(Event.ENTER_FRAME, handleShakeEnterFrame);
    }
}

this should be the top “actions(functions)” on the time line. Now make another actions on the timeline. Now to use this code is very easy, and could be turned into a Document class.

this.shake(mcOrangeBox, 100, 15);