Page 1 of 1

how do i spawn multiple objects by clicking

Posted: Fri May 19, 2017 11:27 am
by slickytree
i tried making it but what just simply happens is that an object spawns and it moves to my mouse's position whenever i click. i think another object is made when i click but the position of the other object updates as well. so it basically just looks like 1 object moving to the mouse's position when i click

here's the code

Code: Select all

objects = {}

function addBox(x,y)
  local box = {}
  box.x = x
  box.y = y
  
  function love.draw() love.graphics.rectangle('fill',box.x,box.y,10,10) end
end

function love.mousepressed(x,y,button,istouch)
  if button == 1 then
    addBox(x,y)
  end
end
sorry if my explanation isn't clear or my code looks like it was made without effort and the mistake could be spotted very easily. it's my first day coding with love ;(

Re: how do i spawn multiple objects by clicking

Posted: Fri May 19, 2017 1:14 pm
by MolarAmbiguity
You are not storing the positions of the box as you create them. As a result you will only ever see one box. You should store them in the objects array you created.

You should also call love.draw() outside of other functions. This is more idiomatic and will help with code structure as your game increases in complexity.

Code: Select all

objects = {}

function addBox(x,y)
  local box = {}
  box.x = x
  box.y = y
  objects[#objects+1] = box
end

function love.mousepressed(x,y,button,istouch)
  if button == 1 then
    addBox(x,y)
  end
end

function love.draw()
    for _,box in pairs(objects) do
        love.graphics.rectangle('fill',box.x,box.y,10,10)
    end
end

Re: how do i spawn multiple objects by clicking

Posted: Sat May 20, 2017 3:27 am
by slickytree
thanks so much!!