Skip to content Skip to sidebar Skip to footer

Create A Square Polygon (random Oriented) From Midpoints In Python

I have a midpoint (x,y) and i need to create a square polygon with random orientation using a 2D (random) planar rotation. def get_square_plot(x, y, side): return [(x-(side/2),

Solution 1:

If I've understood you correctly, this should be able to do what you want:

from math import sin, cos, radians

defrotated_square(cx, cy, size, degrees=0):
    """ Calculate coordinates of a rotated square centered at 'cx, cy'
        given its 'size' and rotation by 'degrees' about its center.
    """
    h = size/2
    l, r, b, t = cx-h, cx+h, cy-h, cy+h
    a = radians(degrees)
    cosa, sina = cos(a), sin(a)
    pts = [(l, b), (l, t), (r, t), (r, b)]
    return [(( (x-cx)*cosa + (y-cy)*sina) + cx,
             (-(x-cx)*sina + (y-cy)*cosa) + cy) for x, y in pts]

print rotated_square(50, 50, 100)

Output:

[(0.0, 0.0), (0.0, 100.0), (100.0, 100.0), (100.0, 0.0)]

Note that in the general case, the resulting coordinates won't be integers.

What this does effectively is first translate each coordinate to the origin by subtracting cx,cy from it, rotates that by the angle, and then un-translates it back by the same amount. This is necessary to compensate for the fact that rotation formulas usually are relative to origin of a coordinate system.

Solution 2:

having determined the four corner coordinates, you can rotate them relative to the origin (or midpoint) using a simple 2D Matrix Rotation:

http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 (search for 2D rotation equation)

x' = x cos(theta) - y sin(theta)
y' = x sin(theta) + y cos(theta)

You can use the built-in Python Math library for the cos/sin functions: http://docs.python.org/2/library/math.html section 9.2.3

Math.cos(theta)
Math.sin(theta)

I hope this is of some use!

Post a Comment for "Create A Square Polygon (random Oriented) From Midpoints In Python"