newbie
newbie

Reputation: 33

How to translate and rotate the coordinate axis about a point in pygame screen?

I'm trying to draw a polygon with DDA line algorithm using pygame.

def Round(a):
    return int(a + 0.5)

def mainloop():
    while True:
        for event in pygame.event.get(): 
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

def Draw():
    DrawPoly((100, 100), 6, 100)
    pygame.display.flip()


def drawDDA(p1, p2, color=[0, 0, 0]):
    x0, y0, x1, y1 = p1[0], p1[1], p2[0], p2[1]
    steps = abs(x0-x1) if abs(x0-x1) > abs(y0-y1) else abs(y0-y1)
    dx = (x1-x0)/steps
    dy = (y1-y0)/steps
    x, y = x0, y0
    gfxdraw.pixel(screen,Round(x),Round(y),color)
    for i in range(int(steps)):
        x += dx
        y += dy
        gfxdraw.pixel(screen,Round(x), Round(y),color)


def DrawPoly(center, n, s, color=[0, 0, 0]):
    cx, cy = center[0], center[1]
    sideAngle = 360/n
    bv1x = cx-s/2
    bv1y = cy - (s/2)*(1/math.tan(math.radians(sideAngle/2)))
    bv2x = cx+s/2
    bv2y = bv1y
    drawDDA((bv1x, bv1y), (bv2x, bv2y), color)
    for i in range(n-1):
        # i want to rotate the coordinate plane about an angle "sideAngle" with (cx,cy) as the center
        # code here
        drawDDA((bv1x, bv1y), (bv2x, bv2y), color)

size = [640, 720]
os.environ['SDL_VIDEO_CENTERED'] = '0'
pygame.init()
screen = pygame.display.set_mode(size)
screen.fill((255, 255, 255))
Draw()
mainloop()

The idea I tried to execute to draw a polygon is

  1. I'm taking a point as center of the polygon
  2. calculating the coordinates of two consecutive points
  3. draw a line between those two points
  4. rotate the whole plane about the center of the polygon by side angle which is (360 degrees/number of sides of the polygon)
  5. now, draw a line with the same coordinates to get another side of the polygon
  6. repeat 4 and 5 for n-2 times to get all the remaining side. (n is the number of sides)

I need a way to rotate the coordinate axis about the center of my polygon.

Upvotes: 2

Views: 373

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

If you can transform Polar coordinates (d, a) to Cartesian coordinate (x, y) with math.sin and math.cos

x = d * cos(a)
y = d * sin(a) 

Change the function DrawPoly:

def DrawPoly(center, n, s, color=[0, 0, 0]):
    x0, y0 = center[0], center[1]
    a =  math.radians(360 / n)
    d = s / 2 / math.sin(a / 2)
    pts = []
    for i in range(n+1):
        sideAngle = math.radians(360 * i / n)
        x = x0 + d * math.cos(sideAngle)
        y = y0 + d * math.sin(sideAngle)
        pts.append([x, y])

    for i in range(n):
        drawDDA(pts[i], pts[i+1], color)

Different polygons with the same side length:

def Draw():
    DrawPoly((100, 100), 3, 100, (192, 0, 0))
    DrawPoly((100, 100), 4, 100, (0, 192, 0))
    DrawPoly((100, 100), 5, 100, (0, 0, 192))
    DrawPoly((100, 100), 6, 100, (0, 0, 0))
    pygame.display.flip()

Upvotes: 3

Related Questions