(solved)How to calculate direction from a object to another in 3d space?

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

Script a object shooting arrow to player. At first use player’s translation minus arrow’s translation after set the same y, then normalize the results to get dir, using move_and_slide(dir * speed) to move the arrow, sometimes the arrow moving direction is right sometimes wrong. After doing some search it seems the translation is local, then change it to get_global_transform().origin, but the results is kind same as before. How to calculate that correctly?
Thanks!
edit: used look at to rotate the arrow, somehow it change the position of the arrow, so change it to rotate, problem solved

:bust_in_silhouette: Reply From: avencherus

var heading = (b.global_transform.origin - a.global_transform.origin).normalized()

changed my script, but still the arrow shoot at position right to player, not exactly at player’s position.

hsjaaa | 2019-02-22 09:52

Is the mesh/sprite or another node of your player moved away from the player’s origin and it just looks like that?

RenenerG | 2019-02-22 10:16

Thanks for your reply, found the arrow shooting base is moved, the transform → translation property is edited to move the base and arrow is instanced as a child of the base. I set the property to (0, 0, 0) the direction is right. But how can I move the base and keep the arrow still shooting at right direction?

hsjaaa | 2019-02-22 11:11

Basically it is physically correct when the speed of the parent is added to the arrow (until air draft comes into play). But that is not helpful here, I guess you don’t want to have physically correct arrow behaviour which would make many things more complicated.

Simply move the arrow out of the parent. (i.e. instantiate as child of the scene root)
Just think about assigning the correct initial position (and or transform) to the arrow.

wombatstampede | 2019-02-22 11:44

Try this add a new node (which base node of everithing) because this cant be local spaced.
Scene tree:
Base
–Node
----Arrow

Or trying move the arrow global position instead local
Or make the arrow should will be not the parent of base when firing

Sry for ma english.

LordViperion | 2019-02-22 11:48

Try to separate the arrow scene and the base scene, using signal to inform the main scene to instance arrow, tried to pass base’s translation or global_transform.origin as a arg but the arrow didn’t spawn at the base’s location and the direction is wrong once the base is not at (0, 0, 0).

hsjaaa | 2019-02-22 12:47