My gun won't spawn bullets where they should spawn

Godot Version

4.3

Question

I am trying to make a projectile weapon in godot 4 3d but the projectiles my gun spawns are spawning in a completely different spot, I use a marker3D “%muzzle” to tell the script where to spawn the bullet, an error I got is
E 0:00:01:0975 gun.gd:9 @ _input(): Condition “!is_inside_tree()” is true. Returning: Transform3D()
<C++ Source> scene/3d/node_3d.cpp:345 @ get_global_transform()
gun.gd:9 @ _input()
so how I understand this, is that the muzzle isn’t in the game scene? the thing is when I did some troubleshooting I used print(muzzle.global_position) and it worked, so it should be in the scene

here is the gun script, I changed global_position to global_transform and it stopped the errors but nothing changed besides that

extends Node3D

@onready var bullet = preload("res://bullet.tscn")
@onready var muzzle = %muzzle

func _ready() -> void:
	await get_tree().process_frame  # Ensures scene is fully ready
	if not muzzle:
		push_error("Muzzle not found! Check the node path.")
	else:
		print("Muzzle is ready at:", muzzle.global_position)

func _input(event: InputEvent) -> void:
	if Input.is_action_just_pressed("left_click"):
		if not is_inside_tree():
			return
		var create_bullet = bullet.instantiate()
		create_bullet.global_transform = muzzle.global_transform
		create_bullet.transform.basis = muzzle.global_transform.basis
		add_child(create_bullet) 
		



I think the problem is you are trying to set the transform

create_bullet.global_transform = muzzle.global_transform
create_bullet.transform.basis = muzzle.global_transform.basis

before you’ve added the node to the scene tree, try moving these lines after

add_child(create_bullet) 
1 Like

ohh… that worked, when I made 2d games I usually put add_child() at the end and it worked, anyways thank you

I think in this case it’s just create_bullet.transform.basis = muzzle.global_transform.basis that needs to be done after. As you are actually trying to get the transform (to get the basis). The error was saying the Transform3D couldn’t be returned as the node isn’t in the tree.

In general you can set properties before adding the node to the scene. In fact the docs say this explicitly in the best practices section.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.