Page 1 of 1

Draw function deleting objects after the end of the loop.

Posted: Tue Oct 22, 2019 5:15 am
by duhspbr
Hello Lovers!

I'm having a lot of headaches with this seemingly simple code.

I'm having difficulty in this line of the code: draw section

when I try to draw, something like

Code: Select all

function love.draw()
	love.graphics.rectangle("fill", player.posX, player.posY, 15, 15)
	love.graphics.rectangle("fill", player.posX + 20, player.posY + 20, 15, 15) #same draw above, but with a different position
	love.graphics.rectangle("fill", player.posX + 50, player.posY + 50, 15, 15) #same
end
Running this code works perfectly, but will be painful for a lot of objects on the screen. To solve this problem, I created a while loop, that draws these objets at the end:

Code: Select all


pos = { x = {150, 180, 190},
	   y = {250, 280, 350}
}

function love.draw()
	local i = 1
	
	while i <= 3 do
		love.graphics.rectangle("fill", pos.x[i], pos.y[i], 15, 15)
		i = i + 1
	end
end
However, it is possible to see the love2d drawing quickly the objects and clean up the screen.

I don't understand the logic beyond Draw() function, because, on the one hand, you can write several times to draw an object, but for the while loop it goes out, it makes no sense. Or would it be something more technical like using Metatables or some OOP attempt?

Thanks for your attention!

Best regards!

Re: Draw function deleting objects after the end of the loop.

Posted: Tue Oct 22, 2019 7:07 am
by CogentInvalid
The code you posted works fine, so something must be going wrong outside of the draw function.

Re: Draw function deleting objects after the end of the loop.

Posted: Tue Oct 22, 2019 2:48 pm
by duhspbr
Man! I found the error!

In my example, I declared in a different way this part:

Code: Select all

function love.draw()
	local i = 1

	while i <= num_obj do
		love.graphics.rectangle("fill", posX[i], posY[i], 15, 15)
		i = i + 1
	end
end
I forgot about the local variable! In my original code, I have declared out of the loop! That's why worked for you, but not for me! haha

Thank you very much!