我正在使用 pygame 在两个任意点之间画一条线。我还想在线的行进方向上朝外的线的末端附加箭头。
在最后粘贴箭头图像很简单,但我不知道如何计算旋转度数以保持箭头指向正确的方向。
这是执行此操作的完整代码。请注意,使用 pygame 时,y 坐标是从顶部开始测量的,因此在使用数学函数时我们取负数。
import pygame
import math
import random
pygame.init()
screen=pygame.display.set_mode((300,300))
screen.fill((255,255,255))
pos1=random.randrange(300), random.randrange(300)
pos2=random.randrange(300), random.randrange(300)
pygame.draw.line(screen, (0,0,0), pos1, pos2)
arrow=pygame.Surface((50,50))
arrow.fill((255,255,255))
pygame.draw.line(arrow, (0,0,0), (0,0), (25,25))
pygame.draw.line(arrow, (0,0,0), (0,50), (25,25))
arrow.set_colorkey((255,255,255))
angle=math.atan2(-(pos1[1]-pos2[1]), pos1[0]-pos2[0])
##Note that in pygame y=0 represents the top of the screen
##So it is necessary to invert the y coordinate when using math
angle=math.degrees(angle)
def drawAng(angle, pos):
nar=pygame.transform.rotate(arrow,angle)
nrect=nar.get_rect(center=pos)
screen.blit(nar, nrect)
drawAng(angle, pos1)
angle+=180
drawAng(angle, pos2)
pygame.display.flip()
我们假设 0 度表示箭头指向右侧,90 度表示指向正上方,180 度表示指向左侧。
有几种方法可以做到这一点,最简单的可能是使用 atan2 函数。如果您的起点是 (x1,y1) 并且您的终点是 (x2,y2) 那么两者之间的线的角度是:
import math
deg=math.degrees(math.atan2(y2-y1,x2-x1))
这将为您提供 -180 到 180 范围内的角度,因此您需要从 0 到 360 的角度,您必须照顾好自己。
我将不得不查找要使用的确切函数,但是如何制作一个直角三角形,其中斜边是所讨论的线并且腿是轴对齐的,并使用一些基本的三角函数来计算基于该线的角度三角形的边长?当然,您将不得不使用已经轴对齐的特殊情况线,但这应该是微不足道的。
此外,这篇关于斜坡的维基百科文章可能会给您一些想法。
只是为了附加到上面的代码,你可能想要一个事件循环,这样它就不会立即退出:
...
clock = pygame.time.Clock()
running = True
while (running):
clock.tick()