我用pygame编写Python游戏,我想制作一个函数,从特定长度的特定方向绘制一条特定方向的线,例如,定义功能将是:def draw_line(position1: (int, int), angle: int, line_length: int, line_width: float, color: Color):
如何计算绘制直线的第二个点?
我有一个问题的原理图,我想得到position2,用pygame画线。
答案 0 :(得分:2)
这是一个数学问题,但是,第2点的x和y坐标是:
(x2,y2) = (x1 + line_length*cos(angle),y1 + line_length*sin(angle))
答案 1 :(得分:1)
你可以使用矢量。 pygame.math.Vector2
类有一个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()