Search code examples
actionscript-3flash-cs4flash-cs3tween

How do I slowdown an animation in AS3 without decreasing the fps


I have this code that I found online that does an infinite rotating gallery, now my problem is that on enter frame it jumps and too fast. I want it to be as fast at after you hover out of the logo.

Here is the code:

//Import TweenMax
import com.greensock.TweenMax;

//Save the horizontal center
var centerX:Number = stage.stageWidth / 2;

//Save the width of the whole gallery
var galleryWidth:Number = infiniteGallery.width;

//Speed of the movement (calculated by the mouse position in the moveGallery() function)
var speed:Number = 0;

//Add an ENTER_FRAME listener for the animation
addEventListener(Event.ENTER_FRAME, moveGallery);

function moveGallery(e:Event):void {

 //Calculate the new speed
 speed = -(0.02 * (mouseX - centerX));

 //Update the x coordinate
 infiniteGallery.x+=speed;

 //Check if we are too far on the right (no more stuff on the left edge)
 if (infiniteGallery.x>0) {

  //Update the gallery's coordinates
  infiniteGallery.x= (-galleryWidth/2);
 }

 //Check if we are too far on the left (no more stuff on the right edge)
 if (infiniteGallery.x<(-galleryWidth/2)) {

  //Update the gallery's coordinates
  infiniteGallery.x=0;
 }
}

and here is the demo »


Solution

  • The speed of the scroller is based on three things:

    1- The frame rate. The ENTER_FRAME event handler gets called on every frame, thus is directly influenced by the frame rate.

    2- The speed damping number. In your case this is equal to 0.02. If you want to slow down the scrolling, make this a smaller number. Try 0.01 for half the speed.

    3- The distance of the mouse pointer to the center x coordinate of your stage. The difference between the mouse pointer and the center of your stage is multiplied by your speed damping number. If you want the movement to stop when you are at or around the center change you code as follows:

    var buffer:Number = 50;
    
    function moveGallery(e:Event):void {
        var diff = mouseX - centerX;
        if (Math.abs(diff) > buffer) 
            speed = -(0.02 * (diff + (diff > 0 ? -buffer : buffer)));
        else
            speed = 0;
    

    AS REQUESTED:

    var centerX:Number = stage.stageWidth / 2;
    var galleryWidth:Number = infiniteGallery.width;
    var speed:Number = 0;
    addEventListener(Event.ENTER_FRAME, moveGallery);
    
    var buffer:Number = 100;
    
    function moveGallery(e:Event):void {
        var diff = mouseX - centerX;
        if (Math.abs(diff) > buffer) 
            speed = -(0.02 * (diff + (diff > 0 ? -buffer : buffer)));
        else
            speed = 0;
    
        infiniteGallery.x += speed;
    
        if (infiniteGallery.x>0) {
            infiniteGallery.x = -galleryWidth / 2;
        }
    
        if (infiniteGallery.x < -galleryWidth / 2) {
            infiniteGallery.x = 0;
        }
    }