zzzzzzzzUP'
We've previously seen in the article Inertia with Actionscript 3.0 how to create a slowing down motion effect.
Now I'd like to show how to obtain an accelerating moving effect, up to an established speed point.
Here is how to do it'
I create an FLA and save it as 'accelerazione.fla' .
I create the Document Class, an AS file saved as ' Accelerazione.as ', implemented like so:
Code:
package
{
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.Event;
import flash.events.MouseEvent;
public class Accelerazione extends Sprite
{
private var sprite:Sprite;
private var arrivo:int=520;
private var accelerazioneX:Number=.4;
private var velocitaX:Number=0;
public function Accelerazione()
{
stage.frameRate=31;
disegnaSprite();
initSpriteListener();
initButtonListener();
}
private function disegnaSprite():void
{
sprite=new Sprite();
sprite.graphics.beginFill(0x666666,100);
sprite.graphics.drawCircle(0,0,25);
sprite.graphics.endFill();
sprite.x=50;
sprite.y=100;
addChild(sprite);
}
private function initSpriteListener():void
{
sprite.addEventListener(Event.ENTER_FRAME,muoviSprite);
}
private function initButtonListener():void
{
riprova_btn.addEventListener(MouseEvent.MOUSE_DOWN,rifai);
}
private function muoviSprite(e:Event):void
{
velocitaX+=accelerazioneX;
sprite.x+=velocitaX;
if(sprite.x>=arrivo)
{
sprite.x=arrivo;
sprite.removeEventListener(Event.ENTER_FRAME,muoviSprite);
}
}
private function rifai(m:MouseEvent):void
{
sprite.removeEventListener(Event.ENTER_FRAME,muoviSprite);
sprite.x=50;
sprite.y=100;
velocitaX=0;
initSpriteListener();
}
}
}
Analysing the above code, you can notice a accelerazione and a velocita (speed) variables.
The accelerazione variable is a constant, while the velocita variable starts from zero, is increased at scheduled intervals by the value of accelerazione, and then fed to the x of the sprite.
The code seems full bodied as I've also used a button to allow for a reply.
Here is the result:
Stay tuned !