How to reparent the player to the correct vehicle?

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

I have a rocketship in my game that the player can hop into by right-clicking on it when nearby. This is how it works:

  1. The rocket detects a click, and after making sure it does not already have a player, calls a function on the root node of the scene.
  2. The root node then makes a copy of the player, frees him from the scene, and adds him to the rocket as a child node.
    I’m not sure how awfully convoluted this is, but it worked alright until I had multiple rocketships - the engine had no clue what to do with that. So I was wondering if I could somehow pass along the identity of the specific rocket that is clicked to the function on the root node through a variable in the parentheses of the function. I tried using “self” or “self.name” but nothing is working. If anyone knows a fix, or if there is an entirely betetr way of doing this, please let me know :slight_smile:
    Thanks!

I’m confident this can be easily resolved. However, the details of the solution are somewhat dependent on your game’s design. I’d suggest that you post the relevant code for review. That should include at least…

  • The root-level function that adds the player to the rocket
  • The code that calls the root-level function
  • Anything else that’s part of the current solution…

And, please, format any code you paste into the forum to make it easily readable. To do that, paste your code, select it, and press the { } button in the forum editor’s toolbar.

jgodfrey | 2020-11-21 00:32

:bust_in_silhouette: Reply From: stormreaver

I have this in my NodeUtil class, which does what you want:

extends Node

func reparent(node,newParent):
	var old_transform = node.global_transform
	var oldParent = node.get_parent()
	
	oldParent.remove_child(node)
	newParent.add_child(node)
	node.global_transform = old_transform

The basic principle is that you need to remove the node from the old parent, then add it to the new parent.

This also retains the object’s transform and coordinates, which is important to understand. If the object was at [1000,1000,1000] before you reparented it, it will still be at [1000,1000,1000] after reparenting it. You’ll need to change its position to something more suitable to the new parent. In your rocket, for example, you’ll want to set its position to something relative to the rocket (like [0,0,0]) after reparenting.