need help, thanks in advance[SOLVED]

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
strikertweny
Prole
Posts: 1
Joined: Sat Jun 22, 2019 4:15 pm

need help, thanks in advance[SOLVED]

Post by strikertweny »

i wonder if someone can help me about my problem
i am trying to spawn multiple blocks the it just keeps ressetting rather than spawning another
so when i try to run it it just spawns 1 block and keeps resetting itself.

i am a beginner at coding and i am trying to learn love2d,
thankyou very much for helping

Code: Select all

 	spawnTimer = 0
        -- add
	local blocks = {}

	function addBlock(x,y,w,h)
		block = {x=x,y=y,w=w,h=h}
		blocks[#blocks+1] = block
		table.insert(blocks,block)
	end

	function blockUpdate(dt)
	-- block spawn timer && spawn
		spawnTimer = spawnTimer + 0.01
		if spawnTimer > 2 then
			local x = love.graphics.getWidth() /2 
			local y = love.graphics.getHeight() /2
			local w = 50
			local h = 50
			addBlock(x,y,w,h)
			print("succes")
			spawnTimer = 0
		end
	  -- block scroll
		for i=1,#blocks do
			local b = block
			b.x = b.x - 1
			print("-5")
		end

	end

	 	function blockDraw()
		for i=1,#blocks do 
			local b = block
			love.graphics.rectangle("fill",b.x,b.y,b.w,b.h)
		end

	end


KayleMaster
Party member
Posts: 234
Joined: Mon Aug 29, 2016 8:51 am

Re: need help, thanks in advance[SOLVED]

Post by KayleMaster »

`block` is global. So what you're essentially doing is putting a reference `block` in every array entry (`blocks`), but then you change it, so every entry is the same block. Try putting a local before it:

Code: Select all

function addBlock(x,y,w,h)
		local block = {x=x,y=y,w=w,h=h}
		blocks[#blocks+1] = block
		table.insert(blocks,block)
	end
Or entirely removing the need to localize `block` and put it straight in the array.

Code: Select all

function addBlock(x,y,w,h)
		blocks[#blocks+1] = {x=x,y=y,w=w,h=h}
		table.insert(blocks,{x=x,y=y,w=w,h=h})
	end
Also, why do you have both table.insert and blocks[#blocks+1]?

Double also - your for loops are wrong, you are setting b to block, but once we localized block to the AddBlock function, it's not there. It seems like you wanted to iterate through the array, but you're missing a line...

Code: Select all

function blockDraw()
		for i=1,#blocks do 
			local b = blocks[i]
			love.graphics.rectangle("fill",b.x,b.y,b.w,b.h)
		end
Same with your other for loop.

Also I'm really confused about the location of blockDraw function. It needs to be outside and to be called in love.draw afterwards. I'm not seeing the whole picture here, but I guess you've got that working.
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 10 guests