luapolygoncoronasdkanchorpoint

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


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(?)


Solution

  • 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.