Page 1 of 1

Putting rectangles in a table and drawing to screen

Posted: Sun Apr 23, 2017 6:47 pm
by boobeebah13
I've been trying to figure out how I could put rectangles (created with love.graphics.rectangle()) into a table and draw them to the screen as you would a tileset. It seems like something that would be easy but I can't seem to figure it out. And if you're wondering, my game requires that the player can change the width and height of the objects, that's why I can't use regular sprites.


and here's the table code, I was planning on adding to the x value in a for loop to draw them in a straight line.

Code: Select all

objects = {
		love.graphics.rectangle("line", rectX, 490, 50, 50),
		love.graphics.rectangle("line", rectX, 490, 50, 50),
		love.graphics.rectangle("line", rectX, 490, 50, 50),
		love.graphics.rectangle("line", rectX, 490, 50, 50),
		love.graphics.rectangle("line", rectX, 490, 50, 50)
}

Re: Putting rectangles in a table and drawing to screen

Posted: Sun Apr 23, 2017 6:53 pm
by Sir_Silver
love.graphics.rectangle, or any of the drawing operations for that matter, don't actually return any values. Instead, what you want to do is something like this:

Code: Select all

local objects = {
    {x = 0, y = 0, w = 50, h = 50},
    {x = 50, y = 100, w = 20, h = 50},
    {x = 100, y = 200, w = 50, h = 100},
    {x = 350, y = 350, w = 10, h = 100},
    {x = 400, y = 500, w = 10, h = 10}
}

function love.draw()
    for i = 1, #objects do
        local obj = objects[i]
        
        love.graphics.setColor(255, 255, 255)
        love.graphics.rectangle("fill", obj.x, obj.y, obj.w, obj.h)
    end
end
Create your objects, store them inside of a table, and then when you want to render them, iterate over the objects in your table in the love.draw callback.