3D direction_to() Vector originates from global center instead of local center

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By CodingLikeADuck

I try to get the angle compared to the X axis from one node to another one in 3d space. For that I first try to get the direction_to vector but it originates from the global center instead of local, messing everything up. I found this out in a separate test environment.
This script + Line2D are part of one of the “ship” nodes (the top one).
I would expect for the normalized vector to use local space → the line point towards the other ship (with 1 lenght because the normalization)? How do I archieve this?

func update_line(target):
var unprojected_pos_1: Vector2 = get_viewport().get_camera_3d().unproject_position(self.global_position)

var direction_to_other_ship = (self.global_position.direction_to(target.global_position))
var unprojected_pos_2 : Vector2 = get_viewport().get_camera_3d().unproject_position(direction_to_other_ship)


enter image description here

:bust_in_silhouette: Reply From: stormreaver

I’m just going to comment on your visualization, as what you have here vs what you are after are two separate issues.

As a side note, I’m pretty bad at mental math, so I won’t take offense if anyone points out an error in my explanation.

Normalized vectors always originate at the origin, and have no concept of global vs local space. Global vs local is all a matter of how you’re using the vector. Without this feature, angle calculations would be difficult at best.

unproject_position expects a final 3D coordinate to be given to it, not a direction. Your first point works because you are using a 3D position in space.

But your second point is using a direction vector (with length of 1) as the parameter, so it is not going to appear in 2D space where you want it. Your second point should be the unprojection of the first 3D point plus the unnormalized 3D direction vector.

Using direction_to is causing you unnecessary grief for your visualization, as the value it returns is normalized (length of 1). You’re better off doing the simple direction/magnitude calculation yourself: (target.global_position.origin - self.global_position.origin), adding that to your first point, then using the result as your unprojection parameter.

Normalized vectors always originate at the origin, and have no concept of global vs local space.

Thanks, that’s exactly the tip I needed to stop banging my head against the wall!
Now I know that this part of my code is correct and actually found the error elsewhere.

For people getting here via google: If you want to get an angle out of it in 3D space use “signed_angle_to()” to also get negative values.

CodingLikeADuck | 2023-06-25 13:10