Page 1 of 1
Spawning multiple objects
Posted: Mon Mar 13, 2017 5:53 pm
by eqnox
Could someone give my code a once over and see if they can see why it isnt working. It is supposed to spawn a black box on mouse click and should be able to do multiple of them. I don't know if I am drawing them wrong and that's why I can't see them. Help would be much appreciated!
Re: Spawning multiple objects
Posted: Mon Mar 13, 2017 6:17 pm
by 0x72
I've added just minor changes.
Code: Select all
local objects
function addBox(x,y)
-- TIP: no need for adding everything to objects.somthing - this is hash part of lua table, read about how lua table works
-- and how it behave as array and as a hash the same time
local box = {}
box.body = love.physics.newBody(world, x, y, "dynamic")
box.shape = love.physics.newRectangleShape(0, 0, 21, 21)
box.fixture = love.physics.newFixture(box.body, box.shape, 5)
table.insert(objects, box)
end
function love.load()
objects = {}
love.physics.setMeter(64)
world = love.physics.newWorld(0, 9.81*64, true)
ground = {}
ground.body = love.physics.newBody(world, 250, 500)
ground.shape = love.physics.newRectangleShape(500, 50)
ground.fixture = love.physics.newFixture(ground.body, ground.shape)
-- TIP: you can treat ground as any other object in your game
table.insert(objects, ground)
love.graphics.setBackgroundColor(255, 255, 255)
love.window.setMode(500, 500)
end
function love.update(dt)
world:update(dt)
end
function love.draw()
love.graphics.setColor(0, 0, 0)
-- TIP: iparis iterate over array elements (the one you've added with table.insert) while pairs would iterate over all elements
-- you could have those boxes in hash part if you'd use pairs here but then you'd have to make up a new key for each of them
-- (e.g. box_1, box_2..., using integers is simpler though)
for _, box in ipairs(objects) do
-- TIP: love.graphics.polygon makes more sense then love.graphics.rectangle here because it accepts points instead of positions+size
-- but don't worry too much, in final game you're probably going to use some sprites anyway.
love.graphics.polygon("fill", box.body:getWorldPoints(box.shape:getPoints()))
end
end
function love.mousepressed(x,y,button,istouch)
if button == 1 then
addBox(x,y)
end
end
function love.keypressed(key)
if key == "escape" then love.event.quit() end
if key == "r" then love.load() end
if key == "n" then addBox(20,20) end
end
also:
the file is supposed to be called
main.lua, not
Main.lua, renaming will save you from bugs in the future
Re: Spawning multiple objects
Posted: Mon Mar 13, 2017 7:01 pm
by eqnox
Thanks so much for that help!