ActionScript: Move object with smooth acceleration and deceleration with inertia
Today a simple sample of code to create an inertia effect in ActionScript 3.0.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
// 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; } |