Search code examples
javalibgdx

How do i change the distance as game accelerates?


I am trying to make a game like Canabalt with JAVA using LibGDX, in the game the background accelerates right to left while the player stays on the same position.The distance increases by 1 every second and the speed accelerates by 0.15f like this:

public void update(float delta){
    timeState += delta;
    speed += 0.15f;

    if(timeState >= 1){
        timeState = 0f;
        distance += 1;
    }

    if (speed > MAX_SPEED) speed = MAX_SPEED;

}

But i don't want the distance to be constant, i want it to change relative to the speed. So as the speed increases the distance starts to increment faster too. And when the max speed is reached the distance increment should also be constant. How can i archieve that?


Solution

  • I think it is probably more straightforward to have distance represent the true distance covered, something like:

    public void update(float delta){
        distance += speed * delta;  //  distance = speed * time
        speed += 0.15f;
    
        if (speed > MAX_SPEED) speed = MAX_SPEED;
    }
    

    That way your variables actually reflect what is happening in the game rather than having to use the fudgy timestate workaround.

    The only difference here is that distance will now need be a float - casting this to an int (like (int)distance) will truncate it and leave it with the integer value you seem to want from your above code.