Today a simple sample of code to create an inertia effect in ActionScript 3.0.
[swf:/wp-content/uploads/2013/09/Flash_acceleration_benoifreslon.com_.swf 550 400]
The character will start to move with smooth acceleration if you press an arrow key.
You can download the source code here : Flash_acceleration_benoifreslon.com.fla
// Copyrights // Benoît Freslon // https://www.benoitfreslon.com import flash.events.KeyboardEvent; import flash.events.MouseEvent; // Constants (You can modify this values) const acceleration:Number = 0.1; const decceleration:Number = 0.9; const speedMax:Number = 5; // Variables var speedX:Number = 0; var speedY:Number = 0; // Key states var leftPressed:Boolean = false; var rightPressed:Boolean = false; var upPressed:Boolean = false; var downPressed:Boolean = false; // Keyboard events stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown); stage.addEventListener(KeyboardEvent.KEY_UP, keyUp); function keyDown(e:KeyboardEvent):void { switch (e.keyCode) { case 37 : leftPressed = true; break; case 38 : upPressed = true; break; case 39 : rightPressed = true; break; case 40 : downPressed = true; break; } } function keyUp(e:KeyboardEvent):void { switch (e.keyCode) { case 37 : leftPressed = false; break; case 38 : upPressed = false; break; case 39 : rightPressed = false; break; case 40 : downPressed = false; break; } } // Enter frame events pig.addEventListener(Event.ENTER_FRAME, enterFrame); function enterFrame(e:Event):void { // If a key is pressed I will increase the speed with the acceleration value if (upPressed) { speedY -= acceleration; } else if (downPressed) { speedY += acceleration; } else { // If the up key and the down key are released I will decrease the speed with the decceleration value speedY *= decceleration; } if (leftPressed) { speedX -= acceleration; } else if (rightPressed) { speedX += acceleration; } else { speedX *= decceleration; } // Limit the speed if (speedX > speedMax) { speedX = speedMax; } if (speedX <-speedMax) { speedX = - speedMax; } if (speedY > speedMax) { speedY = speedMax; } if (speedY <-speedMax) { speedY = - speedMax; } // Move the pig pig.x += speedX; pig.y += speedY; // Display values on HUD tValues.text = "speedX: " + speedX + "\nspeedY: " + speedY; } // Reset pig stage.addEventListener(MouseEvent.CLICK , click); function click(e:MouseEvent):void { pig.x = stage.stageWidth / 2; pig.y = stage.stageHeight / 2; }