从角度和线的长度获取点的位置

Get a point's position from an angle and the length of the line

我正在 Python 编写一个游戏,使用 pygame,我想制作一个函数,从一个点向特定方向绘制一条具有特定长度的线,例如,函数的定义为:def draw_line(position1: (int, int), angle: int, line_length: int, line_width: float, color: Color):

如何计算画线的第二个点?

我有一点问题的原理图,我想得到位置2,与pygame画线。

这是一道数学题,不过没关系,点2的x和y坐标是:

(x2,y2) = (x1 + line_length*cos(angle),y1 + line_length*sin(angle))

你可以只使用向量。 pygame.math.Vector2 class 有一个 from_polar 方法,您可以将所需向量的长度和角度传递给该方法。然后将这个向量添加到第一个点,你就有了第二个点。

import pygame as pg
from pygame.math import Vector2


def draw_line(position, angle, line_length, line_width, color, screen):
    vector = Vector2()  # A zero vector.
    vector.from_polar((line_length, angle))  # Set the desired length and angle of the vector.
    # Add the vector to the `position` to get the second point.
    pg.draw.line(screen, color, position, position+vector, line_width)


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray13')
BLUE = pg.Color('dodgerblue1')

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    screen.fill(BG_COLOR)
    draw_line((100, 200), 30, 120, 2, BLUE, screen)
    pg.display.flip()
    clock.tick(30)

pg.quit()