androidmathgame-physicsgame-developmentacceleration

Game Development: How to add acceleration to velocity?


I have a View which I need to scale with an acceleration, I mean, that when the scale is MIN_SCALE, the velocity must be slow, but when the scale is near of MAX_SALE, the velocity must be more fast. Now my velocity is always the same.

There is a number of frames that the View will use to do it's movement:

numberOfFrames = Math.round((float)ANIMATION_TIME/GameLoopThread.FRAME_PERIOD);
frameCount = 0;

and I calculate the scaleVelocity with that number of frames:

scaleVelocity = (MAX_SCALE-MIN_SCALE)/numberOfFrames;

Each game loop iteration, I update the scale of the view with this code:

if (frameCount<numberOfFrames) {
    currentScale = currentScale + scaleVelocity;
    frameCount++;
}

When frame count has reached the numberOfFrames the animation must end.

How can I add acceleration to this code? take in mind that the acceleration must respect that the view needs to reach the MAX_SCALE at last frame from the frameCount variable.


Solution

  • screenshot from android docs

    Define your interpolator

    INTERPOLATOR = new AccelerateInterpolator();  
    

    while calculating scaleVelocity, get current interpolated value

    float interpolatedValue = INTERPOLATOR.getInterpolation(frameCount / numberOfFrames);
    

    getInterpolation() returns a value between 0(start of animation) and 1(end anim)

    scaleVelocity = (MAX_SCALE-MIN_SCALE)/numberOfFrames * interpolatedValue;  // use min,max func if needed.
    

    mathematical equation of accelerate interpolator is f(x) = x², if you want greater change then create your custom interpolator.

    working test method for animation.

     private void testAnim() {
        int numberOfFrames = 100;//Math.round((float)ANIMATION_TIME/GameLoopThread.FRAME_PERIOD);
        float frameCount = 0;
        float MAX_SCALE = 4;
        float MIN_SCALE = 0.1f;
        float scaleVelocity;
        float currentScale ;
        Interpolator INTERPOLATOR = new AccelerateInterpolator();
    
        do {
            float interpolatedValue = INTERPOLATOR.getInterpolation(frameCount / numberOfFrames);
            scaleVelocity = (MAX_SCALE - MIN_SCALE) * interpolatedValue;
    
            currentScale = Math.max(MIN_SCALE, scaleVelocity);
            ++frameCount;
            Log.d("STACK", "testAnim: currentScale = " + currentScale);
            // apply scale to view.
        } while (frameCount < numberOfFrames);
    
        // finally set final value of animation.
        currentScale = MAX_SCALE;
        // apply scale to view.
    
    }