Search code examples
javaanimationlibgdx

Decreasing One Variable as Another Increases


I am putting together a small game in Java, one of the problems I have encountered is increasing the speed of the animation as the player character's movement speed increases.

To increase the speed of animation, the time each frame of the animation is displayed must be decreased, from a maximum of '0.2' for the slowest speed and '0.1' for the highest speed.

My current code works, but it is quite clearly a little clumsy. Unfortunately, I can't think of an elegant solution to replace it.

public float getAnimationSpeed()
{
    float _absVel = Math.abs(_vel.x);

    if(_absVel > 10 && _absVel <= 50)
    {
        return 0.1f;
    }
    else if(_absVel > 50 && _absVel <= 150)
    {
        return 0.075f;
    }
    else if(_absVel > 150)
    {
        return 0.05f;
    }
    else
    {
        return 0f;
    }
}

You might notice the function may also return a zero, which is used to display the animation as still(For example, when the player character has a velocity of 0, the animation shouldn't be playing).


Solution

  • You can be more dynamic, instead of reasoning with "steps" :

    public float getAnimationSpeed()
    {
        float _absVel = Math.abs(_vel.x);
        float offset = 0; //whatever you want
    
        if(_absVel<=10){
            return 0f;
        }
        else{
            return ((1/_absVel)+offset)f;
        }
    }
    

    You can of course change the "1" and the offset to another value that matches the result you want.

    I hope it helped !

    PS/ You probably also want to check if the result is over your maximum or under your minimum, which I didn't do.