Explication of createRandPoly from PhysicsLab?

I often can’t understand other people’s code until I modify it to make their variable names super explicit and break the statements into smaller steps.

This is my attempt to understand the createRandPoly function in the PhysicsLab example:


function createRandPoly(x,y)
    local numSides = math.random(3,10)
    local radius = math.random(25,75)
    local direction = 0
    local directionIncrement = 2 * math.pi / numSides
    local points = {}

    for i = 1, numSides do
        local distanceFromCenter = vec2(radius,0)
        local pointOnCircumference = distanceFromCenter:rotate(direction)
        local randomOffset = vec2(math.random(-10,10), math.random(-10,10))
        local newPoint = pointOnCircumference + randomOffset
        direction = direction + directionIncrement
        table.insert(points, newPoint)
    end

    local poly = physics.body(POLYGON, table.unpack(points))
    poly.x = x
    poly.y = y
    poly.sleepingAllowed = false
    poly.restitution = 0.25
    debugDraw:addBody(poly)
    return poly
end

…does that seem accurate?

yeah but numSides is numPoints

@skar thank you!!