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

Question:

I’m programming a game in Python, with pygame, and I’d like to make a function that draws a line in a specific direction from a point, with a specific length, for example, the definition of the funcion would be: def draw_line(position1: (int, int), angle: int, line_length: int, line_width: float, color: Color):

What can I do for calculating the second point to draw the line?

I have a little schematic of the problem, I want to get position2, to draw the line with pygame.

enter image description here

Asked By: Arnyminer Z

||

Answers:

This is a math problem, but ok, the x and y coordinate of point 2 are:

(x2,y2) = (x1 + line_length*cos(angle),y1 + line_length*sin(angle))
Answered By: ViG

You can just use a vector. The pygame.math.Vector2 class has a from_polar method to which you can pass the length and angle of the desired vector. Then add this vector to the first point and you have the second point.

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()
Answered By: skrx

Keep in mind that ViG’s answer works the same in 3D; you just have to do the same equation, with the z axis resulting in the same formula as the x axis:

from math import cos, sin

def getPointInDir(x0, y0, z0, angX, angY, angZ, distance):
    """
    x0 / y0 / z0 - The original point from which you are 
    interpolating from.
    angX / angY / angZ - The angles (in degrees) of the three axes.
    distance - The distance (length) from p0 to p1.
    """
    x1 = x0 + distance*cos(angX)
    y1 = y0 + distance*sin(angY)
    z1 = z0 + distance*cos(angZ)
    
    result = [x1, y1, z1]
    return result

You don’t even have to use vectors!

Answered By: KevType
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.