how do i spawn multiple objects by clicking

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
slickytree
Prole
Posts: 4
Joined: Fri May 19, 2017 11:12 am

how do i spawn multiple objects by clicking

Post 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 ;(
MolarAmbiguity
Prole
Posts: 2
Joined: Fri May 19, 2017 1:06 pm

Re: how do i spawn multiple objects by clicking

Post 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
slickytree
Prole
Posts: 4
Joined: Fri May 19, 2017 11:12 am

Re: how do i spawn multiple objects by clicking

Post by slickytree »

thanks so much!!
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot], Google [Bot] and 5 guests