0 votes

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.

in Engine by (103 points)

1 Answer

0 votes

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

by (103 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.