position polygon accurately in Corona SDK? (relative to known vertices - issue is it creates it own centre

577 views Asked by At

Question: How can one position a polygon relative to one of it's known vertice points?

In other words how could I calculate where the auto generated center of the polygon is relative to one of the known vertices (i.e. used in the path)?

e.g. Image placing a specific shape on a map which you make polygon, you then want to position it on the map, however you can't do this accurately without knowing where it's Corona engine created centre is. Extract from API: "The local origin is at the center of the polygon and the anchor point is initialized to this local origin."

PS Actually wondering if I should be using a line and appending points to create effectively a polygon, however perhaps you can't add background color in this case(?)

2

There are 2 answers

1
g.sciacchitano On BEST ANSWER

The center calculated by corona is the center of the bounding box of the polygon.

I assume you have a table with all the points of your polygon stored like that:

local polygon = {x1,y1,x2,y2,...,xn,yn}

1) to find the bounding box of your original points, loop thru all the points; the smallest x and smallest y values will give you the coordinates of the top-left point; the largest x and y values are for the bottom-right point;

local minX = -math.huge
local minY = -math.huge
local maxX = math.huge
local maxY = math.huge

for i=1, #polygon, 2 do
    local px = polygon[i]
    local py = polygon[i+1]
    if px > maxX then maxX = px end
    if py > maxY then maxY = py end
    if px < minX then minX = py end
    if py < minY then minY = py end
end

2) find the center of this bounding box:

local centerX = (maxX - minX)/2
local centerY = (maxY - minY)/2

3) add the center point to the top-left point

local offsetX = centerX + minX
local offsetY = centerY + minY    

4) add this offset to the corona polygon to place it in the same position as the original polygon.

Should work bot I have not tested it. Let me know.

0
personalnadir On

I used a variant on the solution above as I couldn't get it to work. Essentially I found the minimum vertex coordinates in each dimension and added them to the polygon position. By comparing them to the contentBounds positions, I can compute the difference between where I thought the minimums would be and where they are.

local min_x = math.huge
local min_y = math.huge
for v = 1, #vertices, 2 do
    min_x = math.min(min_x, vertices[v])
    min_y = math.min(min_y, vertices[v + 1])
end

local poly = display.newPolygon(x, y, vertices)
local offset_x = (x + min_x) - poly.contentBounds.xMin
local offset_y = (x + min_y) - poly.contentBounds.yMin
poly:translate(offset_x, offset_y)