在 pygame 中,二维向量运算的实现是pygame.math.Vector2 https://www.pygame.org/docs/ref/math.html#pygame.math.Vector2.
定义一个Vector2
鼠标位置和三角形中心的对象。计算中心点到鼠标位置的向量角度(.angle_to() https://www.pygame.org/docs/ref/math.html#pygame.math.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() https://www.pygame.org/docs/ref/math.html#pygame.math.Vector2.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 https://www.pygame.org/docs/ref/math.html#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
请注意,此版本可能更快。它需要一个math.sqrt
操作,相比math.atan2
这可能是由.angle_to()
and math.sin
分别math.cos
这可能是由.rotate()
,前一种算法的。
结果坐标是一样的。