Search code examples
lualove2d

Löve2D: Objects disappear but body still exists


I'm doing a platformer and I'm trying to do a loading system for levels, but I have a problem, there is the part of my code :

 --main.lua
require "level1" ; require "level2"
function love.load()
              love.physics.setMeter(64)
              world = love.physics.newWorld(0,9.81*64, true)
   --[...]
   level = 1
end

function love.draw()
   if level == 1 then draw_level1()
   elseif level == 2 then draw_level2() end
end

function love.update(dt)
   world:update(dt)
   if gs == "loading2" then unload_level2() ; load_level2() end
   --[...]
 end

function love.keypressed(key)
   if key == "u" then level = 2 gs = "loading2" else gs = "normal" end
end

level1.lua :

--level1.lua
function load_level1(world)
obj1 = {}
obj1.body = love.physics.newBody(world, 111,111, "dynamic")
obj1.shape = love.physics.newRectangleShape(28,28)
obj1.fixture = love.physics.newFixture(obj1.body,obj1.shape)
end
function unload_level1()
 obj1 = nil
end
function draw_level1()
   love.graphics.polygon("line", obj1.body:getWorldPoints(obj1.shape:getPoints()))
end

And level2.lua it's the same but with another rectangle, and functions like "draw_level2()"

The problem is that when I press U button, the objects disappear, but their body is still there (When the player touch them, the collision happens but they are invisible) How can I do ?


Solution

  • Firstly, obj1 = nil will not work. You need to destroy them too. This is done by doing obj1:destroy(), as outlined here.

    Secondly, in love.update, the level is being destroyed and created every level. You may want to hack in a quick variable that is flipped off (loaded = true) once you have loaded the new level.

    Of course, a long term solution for this would be to write a proper level loading "class" - but assuming you are a beginner, this should be fine for now.