Instanced node not producing instance of another node

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

I have a player scene that can move and shoot a bullet. But when I instance the player in another scene, the shooting behavior no longer works.

The bullet has a sprite, a CollisionShape2D, and a very simple script that manages its movement. The player script includes the following code that manages the bullet (“Shootport1” is a Position2D child object of Player):

export(PackedScene) var Bullet = load("res://Combat/Bullet.tscn")
func bshoot():
	var b = Bullet.instance()
	get_tree().root.get_child(0).add_child(b) 
	b.position = $Shootport1.position

When I play the “player” scene, the bullet spawns and moves just fine. But I have a “template” scene that has a player child object, and the player moves but does not shoot.

There’s no script attached to the template scene. I tried adding a script that loads Bullet.tscn, but that didn’t change anything. Currently, the template scene has nothing but the child player node.

I also tried replacing get_tree().root.get_child(0) with owner, with no luck there either.

My best guess is that there is something at work in Godot’s scene tree that I don’t understand yet. I’m very new to this.

:bust_in_silhouette: Reply From: ramazan

try

onready  var Bullet = load("res://Combat/Bullet.tscn")
onready var main = get_tree().current_scene
   func bshoot():
   var b = Bullet.instance()
   //get_tree().root.get_child(0).add_child(b) 
   main.add_child(b)
  // b.position = $Shootport1.position
     b.position = $Shootport1.global_position

Thanks, this worked!

I’m curious, though. Replacing position with global_position was key to making the bullets appear in the template scene, and they’re behaving the way I want them to there. However, in the player scene by itself, this change causes the point from which the bullets spawn to move at twice the rate that the player does (so moving down 30 pixels causes the bullets to appear an extra 30 pixels below the Position2D). It’s more important that the behavior works when the player is loaded into other scenes, but I’m wondering why this is happening, if you have any insight. I don’t want to end up spending time struggling with similar bugs that aren’t actually bugs :slight_smile:

cteranodon | 2022-08-04 23:21