How to make a node inherit another node's position and rotation with code

Godot Version

4.7.1

Question

I’m struggling to find a good way to make my character’s gun switch between different hands, my current implementation works like this but has unwanted side effects:

in the code of the weapon:

func _physics_process(_delta: float) -> void:
	if gunposition == 0:
		global_transform = lefthandgunpos.get_global_transform_interpolated()
	elif gunposition == 2:
		global_transform = righthandgunpos.get_global_transform_interpolated()

This creates some delay when moving the gun around (looking about or playing an animation) here’s an example of how it looks in practice:

Then I tried to update the position of the gun in _process instead:

func _process(_delta: float) -> void:
	if gunposition == 0:
		global_transform = lefthandgunpos.get_global_transform_interpolated()
	elif gunposition == 2:
		global_transform = righthandgunpos.get_global_transform_interpolated()

this produced these results where the issue was much worse:

Then i decided to try updating the gun’s position to the Marker3D’s regular global transform instead of the interpolated version using this code in the _physics_process function:

func _physics_process(_delta: float) -> void:
	if gunposition == 0:
		global_transform = lefthandgunpos.get_global_transform()
	elif gunposition == 2:
		global_transform = righthandgunpos.get_global_transform()

This produced these results where again there is some delay when moving the gun around:

I’m really not sure what to do, earlier on i just had the gun as a child of my left hand’s gunposition Marker3D which didn’t present any of these issues but i can’t do that anymore because i need to switch what Marker3D it’s a child of which creates quite a lot of errors due to different scripts referencing the gun’s position in the tree

You could just reparent it to either hand. It sound like you already have a marker at either hand. If you parent it to them, the gun will automatically inherit the hand’s transform.

In the gun script just type reparent(marker3d reference). Depending on how it works, you could try it directly or (if not working) with call_deferred.

Try moving the gun node to some place after the skeleton in the scene tree.

I ended up reading more of the documentation and decided to try out using a pair of RemoteTransform3D nodes to update the transform of the gun using this code:

func _physics_process(_delta: float) -> void:
	if gunposition == 0:
		righthandguntransform.update_position = false
		righthandguntransform.update_rotation = false
		lefthandguntransform.update_position = true
		lefthandguntransform.update_rotation = true
	elif gunposition == 2:
		lefthandguntransform.update_position = false
		lefthandguntransform.update_rotation = false
		righthandguntransform.update_position = true
		righthandguntransform.update_rotation = true

this yielded much better results: