如何在pygame屏幕上围绕一个点平移和旋转坐标轴?

2024-10-02 08:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pygame使用DDA直线算法绘制多边形

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

我试图画一个多边形的想法是

  1. 我取一个点作为多边形的中心
  2. 计算两个连续点的坐标
  3. 在这两点之间画一条线
  4. 以边角(360度/多边形边数)围绕多边形中心旋转整个平面
  5. 现在,用相同的坐标画一条线,得到多边形的另一侧
  6. 重复4和5次n-2次,以获得所有剩余侧边。(n是边数)

我需要一种绕多边形中心旋转坐标轴的方法


Tags: defabssteps多边形screenpygamecolorcenter
1条回答
网友
1楼 · 发布于 2024-10-02 08:20:37

如果您可以使用math.sinmath.cosPolar coordinatesda)转换为Cartesian coordinatexy

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

更改函数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)

具有相同边长的不同多边形:

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

相关问题 更多 >

    热门问题