Search code examples
javaandroidandroid-studiolibgdx

Speed of objects in libGDX


What is the correct way to move objects in-game with the given speed in libGDX? Eg. I have a circle at the bottom of the screen and I want to move it to the top with speed 10 pixels per second. All phones have different speeds so delta time of render function on every phone is different so how I can do it?


Solution

  • I'm not sure what you exactly mean by this:

    All phones have different speeds so delta time of render function on every phone is different...

    But I think your understanding of delta value in rendering process is incorrect. As you probably know already, the render method is called multiple times per second, and after every finished call to render method the screen is updated. How many times the render method is called can be found by checking Gdx.graphics.getFramesPerSecond(). So what is the purpose of delta value, exactly? delta is simply the time span between the current frame (this render call) and the last frame (render call just before the current one) in seconds.

    From physics we know that distance = velocity * time.

    So, to move object by the distance of 10 units per 1 second (unit can be pixels, meters, etc... -- this actually depends on your camera and world rendering logic), we have to compute correct traveled distance for current frame. We know the velocity and the elapsed time (delta). We can compute next position like this

    public void render(float delta) {
        float velocity = 10.0f; // actually 10.0units / 1s
        position = position + velocity * delta; // position can be circle.y to travel up
    }