python - 如何在pygame中将三角形旋转到一定角度?

标签 python python-3.x pygame

我需要在屏幕中心旋转一个三角形(不是图像)。我看到其他人回答过这个问题,但是三角形不能指向上。

我尝试过使用其他人的功能,但他们只看到部分功能,就像我上面提到的功能。

import pygame
disp=pygame.display.set_mode((200,200))
import math
def rotate_triange(mouse_pos,triangle_pos):
    #The code here
import time
while True:
    time.sleep(1)
    pygame.Surface.fill(disp,(255,255,255))
    center = (100,100)
    radius = 10
    mouse_position = pygame.mouse.get_pos()
    for event in pygame.event.get():
            pass 
    points = rotate_triangle((100,100),mouse_position)
    pygame.draw.polygon(disp,(0,0,0),points)
    pygame.display.update()

最佳答案

在 pygame 中,二维向量运算在 pygame.math.Vector2 中实现.

为鼠标位置和三角形的中心定义一个 Vector2 对象。计算向量从中心点到鼠标位置的角度(.angle_to()):

vMouse  = pygame.math.Vector2(mouse_pos)
vCenter = pygame.math.Vector2(center)
angle   = pygame.math.Vector2().angle_to(vMouse - vCenter)

围绕 (0, 0) 定义三角形的 3 个点,并将它们旋转角度 ( .rotate() )

points = [(-0.5, -0.866), (-0.5, 0.866), (2.0, 0.0)]
rotated_point = [pygame.math.Vector2(p).rotate(angle) for p in points]

为了计算最终的点,这些点必须按三角形的中心进行缩放和平移:

triangle_points = [(vCenter + p*scale) for p in rotated_point]

看例子:

import pygame
import math

def rotate_triangle(center, scale, mouse_pos):

    vMouse  = pygame.math.Vector2(mouse_pos)
    vCenter = pygame.math.Vector2(center)
    angle   = pygame.math.Vector2().angle_to(vMouse - vCenter)

    points = [(-0.5, -0.866), (-0.5, 0.866), (2.0, 0.0)]
    rotated_point = [pygame.math.Vector2(p).rotate(angle) for p in points]

    triangle_points = [(vCenter + p*scale) for p in rotated_point]
    return triangle_points

disp=pygame.display.set_mode((200,200))

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    mouse_position = pygame.mouse.get_pos()
    points = rotate_triangle((100, 100), 10, mouse_position)

    pygame.Surface.fill(disp, (255,255,255))
    pygame.draw.polygon(disp, (0,0,0), points)
    pygame.display.update()

算法的一个版本,没有使用pygame.math.Vector2 ,看起来如下:

def rotate_triangle(center, scale, mouse_pos):

    dx = mouse_pos[0] - center[0]
    dy = mouse_pos[1] - center[1]
    len = math.sqrt(dx*dx + dy*dy)
    dx, dy = (dx*scale/len, dy*scale/len) if len > 0 else (1, 0)

    pts = [(-0.5, -0.866), (-0.5, 0.866), (2.0, 0.0)]
    pts = [(center[0] + p[0]*dx + p[1]*dy, center[1] + p[0]*dy - p[1]*dx) for p in pts]
    return pts

注意这个版本可能更快。与 .angle_to()math 可能使用的 math.atan2 相比,它需要一个 math.sqrt 操作。 sinmath.cos 可能是前一个算法的 .rotate() 使用的。 结果坐标相同。

关于python - 如何在pygame中将三角形旋转到一定角度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58100335/

相关文章:

python - Pygame:国际象棋中的网格/棋盘对齐

python - 将破折号绘图嵌入到 html 中

python - 使用 Github API 获取所有存储库的最后一次提交

python - 有没有内置的方法可以在 Python 中使用内联 C 代码?

给定起始字符串的 Python 暴力组合

python - pygame.error : SavePNG: could not open for writing?

python - 计算两个流程步骤之间的平均天数

python - 欧拉项目 #22 Python,缺少 2205 个点?

python - 在树莓派2上的临时文件中读取图像

python - Pygame def 函数