【问题标题】:How to translate and rotate the coordinate axis about a point in pygame screen?如何围绕pygame屏幕中的一个点平移和旋转坐标轴?
【发布时间】:2021-09-05 19:58:56
【问题描述】:

我正在尝试使用 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是边数)

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

【问题讨论】:

  • 我有兴趣围绕一个点旋转轴

标签: python pygame


【解决方案1】:

如果您可以将Polar coordinatesda)转换为Cartesian coordinatexy)与math.sinmath.cos

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

【讨论】:

  • 谢谢!这很好用,但有什么方法可以让平面绕一个点旋转?就像 opengl 中的 glRotatef() 函数
  • @newbie 我不明白你的意思。尝试为角度添加一个常数值:sideAngle = math.radians(360 * i / n - rotate_degree)
  • 我们在 pygame 中有什么函数可以像 opengl 中的 glRotatef() 和 glTraslatef() 函数一样工作吗?
  • @newbie 不,你必须自己做。 Pygame 仅用于教育目的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 2018-02-25
  • 1970-01-01
相关资源
最近更新 更多