The code below is a program that creates rectangles that obey gravity from touches on the screen. I don’t have any troubleshooting questions for this, but I want to know what a certain block of code means. The entire program is below followed by the section I don’t understand.
The Entire Code:
-- Main Class
function setup()
print("Welcome to BOX STACKER!!!")
boxes = {}
local ground = Box:createBox(WIDTH/2, 10, WIDTH, 20, 0)
ground.type = STATIC
table.insert(boxes, ground)
end
function touched(touch)
if touch.state == BEGAN then
table.insert(boxes, Box:createBox(touch.x, touch.y, math.random(20, 80), math.random(20, 80), 0, vec2(touch.x, touch.y)))
end
end
function collide(contact)
if contact.state == BEGAN then
sound(DATA, "ZgNAHAAfQEBATExAAAAAAFBxST5jD7M+TABAf0BAQEBAQEBA")
end
end
function draw()
background(40, 40, 50)
for k, box in pairs(boxes) do
Box:drawBox(box)
end
end
-- Box Class
Box = class()
function Box:createBox(x, y, w, h, r)
local box = physics.body(POLYGON, vec2(-w/2, h/2),
vec2(-w/2, -h/2), vec2(w/2, -h/2), vec2(w/2, h/2))
box.x = x
box.y = y
box.angle = r
box.interpolate = true
box.restitution = 0
return box
end
function Box:drawBox(box)
pushStyle()
pushMatrix()
stroke(148, 224, 135, 255)
translate(box.x, box.y)
rotate(box.angle)
if box.shapeType == POLYGON then
strokeWidth(3.0)
local points = box.points
for j = 1,#points do
a = points[j]
b = points[(j % #points)+1]
line(a.x, a.y, b.x, b.y)
end
end
popMatrix()
popStyle()
end
The Section I Don’t Understand:
function Box:drawBox(box)
pushStyle()
pushMatrix()
stroke(148, 224, 135, 255)
translate(box.x, box.y)
rotate(box.angle)
if box.shapeType == POLYGON then
strokeWidth(3.0)
local points = box.points
for j = 1,#points do
a = points[j]
b = points[(j % #points)+1]
line(a.x, a.y, b.x, b.y)
end
end
popMatrix()
popStyle()
end
Can anyone explain what this section of code means line by line? I want to be able to understand it so I can utilize it in other programs. I’d appreciate the effort. Thank you.