简体   繁体   中英

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?

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
}

You can set the delta time with the libGDX method:

world.step(Gdx.graphics.getDeltaTime());

At the end of the render() method. This allows to libGDX manage the FPS .

To adapt the objects speed as you like you can user the Pixel Per Meter Factor: http://seanballais.github.io/blog/box2d-and-the-pixel-per-meter-ratio/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM