0 votes

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.

Godot version 3.4.4
in Engine by (15 points)

1 Answer

+1 vote
Best answer

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
by (749 points)
edited by

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 :)

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 Frequently asked questions and 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 [email protected] with your username.