获取任何可以旋转的正多边形的点

2024-03-28 13:33:35 发布

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

我试图画任何正多边形,所以从三角形到有很多角的多边形,它看起来像一个圆。为了更简单,它们必须是规则的,所以一个正常的五边形/六边形/八角形等。我希望能够旋转它们。我试着画一个圆,然后用360除以我想要的点的数量,在圆的周围每n度创建一个点,把这些点放到pygame.draw.polygon()然后创建我想要的形状,问题是它的大小不合适,我还想能够拉伸形状,所以有不同的宽度和高度

def regular_polygon(hapi, x, y, w, h, n, rotation, angle_offset = 0):
    #angle_offset is the starting angle in the circle where rotation is rotating the circle
    #so when its an oval, rotation rotates the oval and angle_offset is where on the oval to start from
    if n < 3:
        n = 3

    midpoint = pygame.Vector2(x + w//2, y + h//2)
    r = sqrt(w**2 + h**2)
    #if angle_offset != 0:
        #w = (w//2)//cos(angle_offset)
    #if angle_offset != 90:
        #h = (h//2)//sin(angle_offset)
    w,h = r,r

    points = []

    for angle in range(0, 360, 360//n):
        angle = radians(angle + angle_offset)
        d = pygame.Vector2(-sin(angle)*w//2, -cos(angle)*h//2).rotate(rotation) #the negative sign is because it was drawing upside down

        points.append(midpoint + d)
    #draws the circle for debugging
    for angle in range(0, 360, 1):
        angle = radians(angle + angle_offset)
        d = pygame.Vector2(-sin(angle)*w//2, -cos(angle)*h//2).rotate(rotation)
        pygame.draw.rect(screen, (0,255,0), (midpoint[0] + d[0], midpoint[1] + d[1], 5, 5))

    pygame.draw.polygon(screen,(255,0,0),points)

enter image description here

红色的正方形是上面的函数所做的,后面的蓝色正方形是它应该做的

如您所见,圆确实与矩形的边对齐,但由于圆的角度不均匀,func生成的矩形不正确

我想我需要把圆变成一个椭圆形,但是我不知道如何找到它的宽度半径和高度半径。目前我用毕达格算出了半径

这就是当我不改变宽度或高度时发生的情况

enter image description here


Tags: theinif宽度高度ispygameoffset
1条回答
网友
1楼 · 发布于 2024-03-28 13:33:35

我找到了解决办法

w *= math.sqrt(2)h *= math.sqrt(2)非常有效。我不太懂数学,但经过反复试验,这是可行的。你可能会找到数学here,但我只是将宽度和高度乘以一个数字,然后在排列时打印出这个数字,它非常接近sqrt(2)

相关问题 更多 >