Trouble with Transforms: Positioning a parent object based on a grandchild

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

I am trying to position a node based on one of it’s grandchildren and I am stuck on how to make the necessary transformations.

For analogy, my situation is this:

I have a tank that needs to be positioned, based on knowing where it’s gun is aiming and it’s distance from the target.

The gun is a grandchild of the tank body, and the other nodes in between have been rotated / translated relative to the tank body - so I need some way to account for the difference in transform between the tank and the gun.

I don’t know how to get that difference in transform, or apply it - and I am sure there must be some approach but I’ve read the docs on Spatial and Transform and am missing it.

I am able to position the entire tank in the right place using this approach:

  • set the tank’s transform to the target’s transform
  • rotate it to the reverse angle from the gun to target
  • translate it the distance from the target

The trouble is, this just positions the tank where the gun should be, and I need to adjust that so the gun is in the right place, with the body relative to it. Almost as though the gun was the parent (though this isn’t an option in my case).

Does anyone know the solution or have an idea how to approach this transforms trouble? It must not be a super rare case, that a parent object is to be positioned based on the relationship between one of its children and world space.

Many thanks in advance for looking at this.

:bust_in_silhouette: Reply From: potato

I haven’t worked my problem out yet, but the answer to how to un-transform a parent to a child position is to multiply by the transform.inverse of each node in between. Here’s the code that does that:

var next_node = grandchild
	while next_node != parent:
		bot.transform = bot.transform * next_node.transform.inverse()
		next_node = next_node.get_parent_spatial()

Thanks to BadWolf (MunWolf) via Discord for that