ShakingEffect Manager for Games

January 2nd, 2012 by aabhaanjan

images

[xml]
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;

public class ShakingEffect extends MovieClip
{
private var _posX:Number;
private var _posY:Number;
private var _refObject:Object;
private var _timer:Timer;
private var _isTimerStop:Boolean = false;
private var _interval:int ;
private var _strength:int;

public function ShakingEffect()
{
super();
}
/*
* @params :
* @__obj:pass the object on which you want to put the effect.
* @__interval:Pass the interval of shaking effect.
* @__strength:Passing this you can control the speed of shaking effect.
*/
public function startShake(__obj:Object,__interval:int,__strength:int):void {
_refObject = __obj;
_posX = _refObject.x;
_posY = _refObject.y;
_interval = __interval;
_strength = __strength;
startTimer();
}
/*
* @Comments: Here we are starting the timer. The Shaking effect will continue untill you stop the timer.
*/
private function startTimer():void{
_timer = new Timer(__interval);
_timer.addEventListener(TimerEvent.TIMER, shakeObject);
_timer.start ()
}

private function shakeObject(evt:Event):void {
if(!_isTimerStop){
_refObject.x = _posX+ getMinusOrPlusValues()*(Math.random()*_strength);
_refObject.y = _posY+ getMinusOrPlusValues()*(Math.random()*_strength);
}
}

/*
* @Comments: By Calling this function you can stop the shaking effect.
*/
public function stopShake():void {
stopTimer();
resetObjectPosition();
}

private function resetObjectPosition():void
{
_refObject.x = _posX;
_refObject.y = _posY;
}

private function stopTimer():void
{
_timer.stop();
_isTimerStop = true;
_timer.removeEventListener(TimerEvent.TIMER, shakeObject);

}

private function getMinusOrPlusValues():int{
var rand : Number = Math.random()*4;
if (rand<1) return -1 else return 1; } } } [] /xml