基于终点的旋转

dir*_*ion 2 python geometry pygame

我正在使用pygame在两个任意点之间画一条线.我还想在行的方向向外朝向线的末尾添加箭头.

它很简单,可以在最后粘贴一个箭头图像,但我不知道如何计算旋转度以保持箭头指向正确的方向.

Nik*_*win 9

这是完成代码的完整代码.请注意,使用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()
Run Code Online (Sandbox Code Playgroud)