Page 1 of 1

Multiple shapes on screen

Posted: Wed Aug 10, 2016 6:19 pm
by erawein
For example multiple rectangles on screen, varying in sizes and positions.
I don't really know where to start.
I don't know if there's a way to draw more than one shape on screen rather than writing code for each one, is there an easier way to do this?

Re: Multiple shapes on screen

Posted: Wed Aug 10, 2016 6:53 pm
by 4aiman
Either you write a code for every shape or create some table with properties of your shapes, traverse that and draw the elements.
So it's either

Code: Select all

love.graphics.rectangle(x,y,width,height)
or

Code: Select all

sometable={
   {type="rect", x=10, y=23, w=10,h=58,},
   {type="line", x=140, y=53, w=70,h=35,},
   {type="circle", x=1210, y=27, w=40,h=34,}
}
for k,v in ipairs(sometable) do
   love.graphics[v.type](v.x,v.y,v.w,v.h)
end
Note, that it's a good idea to declare things you'll need everywhere just once.
Also, to draw anything you should put those "love.graphics.*" calls inside love.draw.

Edit:
While classes may come in handy, there's no actual need for those here.
Writing constructors may be too frustrating for newbies.
Especially when they need something as simple as drawing some shapes.
Anyway, it's up to TS to decide.

Re: Multiple shapes on screen

Posted: Wed Aug 10, 2016 6:57 pm
by Tjakka5
What you want is a class that can create objects.
A class is a piece of code that can create a (theoretical) infinite amount of things that share a similar behavior.

Code: Select all

local Box = {} -- This is our Class
Box.list = {}  -- Our class has a 'list' variable to hold all the objects

function Box.new(x, y, w, h)
   local box = {} -- Create a new object..
   box.x = x or 0 -- ..And set its variables
   box.y = y or 0
   box.w = w or 0
   box.h = h or 0

   table.insert(Box.list, box) -- After creation we plop it into the Class' list.
   return box -- And we return it so we can use it later on.
end

function love.draw()
   for _, box in ipairs(Box.list) do -- We loop trough all the objects in the Class' list
      local x, y = box.x, box.y -- We get the x, y..
      local w, h = box.w, box.h -- ..Width and height.
      love.graphics.rectangle("fill", x, y, w, h) -- Then draw the object accordingly.
   end
end

Box.new(10, 10, 50, 50)    -- Spawns a box at [10, 10], with a width and height of 50px
Box.new(100, 100, 20, 20)  -- Spawns a box at [100, 100], with a width and height of 20px