Physics world recreation

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
mihacooper
Prole
Posts: 5
Joined: Mon Aug 22, 2016 8:51 am

Physics world recreation

Post by mihacooper »

Hello everyone!

I faced with a problem of physics (Box2d) world recreation. I mean that physics works different when I create -> destroy -> create the same world again.

I have made simple example here. It shows the speed of failing object:

Code: Select all

total_time = 0

function recreate_world()
    -- If physics world exists destroy it!
    if world then
        world:destroy()
        -- Just to be sure
        world = nil
        collectgarbage()
    end

    -- Create physics world
    world = love.physics.newWorld(0, 10, true)
    love.physics.setMeter(64)

    -- Create object
    player = {}
    player.body = love.physics.newBody(world, 0, 0 , "dynamic")
    player.shape = love.physics.newCircleShape(10)
    player.fixture = love.physics.newFixture(player.body, player.shape, 10)
end

function love.load()
    recreate_world()
end

function love.update(dt)
    total_time = total_time + dt
    world:update(dt)

    -- Recreate physics world each 5 seconds
    if total_time >= 5 then
        player_speed = math.abs(player.body:getY() / total_time)
        print(player_speed .. " pixels per second")

        recreate_world()
        total_time = 0
    end
end
Each 5 seconds it prints the speed of object and recreate the same world again. And here is output of this program:

Code: Select all

53.349362755674 pixels per second
25.007504284116 pixels per second
25.010326393036 pixels per second
25.009385496829 pixels per second
25.012307404012 pixels per second
25.00637001891  pixels per second
25.01000082252  pixels per second
As you can see physics of first world works different comparing to all other.

What am I doing wrong or it's known bug?
User avatar
ivan
Party member
Posts: 1918
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Physics world recreation

Post by ivan »

Your code uses variable dt. So you are running the simulation for a different amount of time.
The longer you run the simulation the more the object will accelerate due to gravity.

You need to use a constant time step if you want perfectly consistent behavior.
For things like replays (with variable time step), you could record 'dt' each frame and re-use that.
mihacooper
Prole
Posts: 5
Joined: Mon Aug 22, 2016 8:51 am

Re: Physics world recreation

Post by mihacooper »

Thanks for reply but the problem was that I set meter of physics world after creation of first world. I have found this mistake right after this post was published :3

The problem solved :cool:
Post Reply

Who is online

Users browsing this forum: Bing [Bot], rabbitboots and 3 guests