How to trace a line between two objects in Ursina Engine

Viewed 235

I want to draw a simple 2D line between the origin and a moving player object. I've tried using a separate entity that always looks at the player entity:

class Body(Entity):
    def __init__(self, head: Head):
        super().__init__(model="line", color=color.orange, scale=0)
        self.origin = Vec2(0, 0)
        self.head = head

    def update(self):
        self.look_at_2d(self.head)
        self.scale = distance(self, self.head)

But the line is still centered at the origin and has the wrong orientation, the 'surface' is faced to the player, not the tip:

Line facing the wrong way

How can I properly adjust the rotation and position of the line?

1 Answers

Solution

def update(self) -> None:
    if self.active:
        self.position = Vec2(self.head.x / 2, self.head.y / 2)
        self.rotation = (0, 0, degrees(atan(self.head.x / (self.head.y or 1))) + 90)
        self.scale = distance(self.origin, self.head)

You can't determine the position of the line tips, so position it on the center between the origin and the dot.

The rotation wanted is the angle between between the line at x = 0 and the dot. Imagining the whole problem as a right triangle allows for using trigonometry here.

The distance x of the dot from origin over the distance y is the tangent of the angle. So the arc tangent of that gives us the angle in radians, which we convert into degrees.

Related