[Projectile Spawn] Projectiles are flickering in wrong position when spawing

Godot Version

4.3

Question

Hi guys

Context:
I’m a completely beginner to Godot (and game development in general).
My current project is a “playground” roguelike game, so that I can learn and test different mechanics, so that later I can apply them in a “real project” scenario.

Problem:
I’ve implemented a shooting mechanic and somewhat managed to get the projectile spawing from the muzzle following the video tutorial Tutorial Link. However, the projectile appears somewhere else first, and then move to the right location.

Any ideas why this is happening?

Video: https://www.youtube.com/watch?v=Ntx1vVTAWqs


Code Snippets:

player.gd

extends CharacterBody2D

const SPEED = 200.0
var direction: Vector2 = Vector2.ZERO

@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D

func _process(_delta):
	direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	
func _physics_process(_delta: float) -> void:
	velocity = direction * SPEED
	
	if (direction == Vector2.ZERO):
		animated_sprite.play("idle")
	else:
		animated_sprite.play("run")
		
	if direction[0] > 0:
		animated_sprite.flip_h = false
	if direction[0]  < 0:
		animated_sprite.flip_h = true
		
	move_and_slide()

assault_rifle.gd

extends Node2D
@onready var sprite: Sprite2D = $Sprite2D
const BULLET = preload("res://scenes/bullet.tscn")
@onready var muzzle: Marker2D = $Sprite2D/Marker2D
const FIREBALL = preload("res://scenes/fireball.tscn")


# Called when the node enters the scene tree for the first time.
func _process(_delta: float) -> void:
	look_at(get_global_mouse_position())
	rotation_degrees = wrap(rotation_degrees, 0, 360)
	if rotation_degrees > 90 and rotation_degrees < 270:
		sprite.flip_v = true
		muzzle.scale.y = -1
	else:
		sprite.flip_v = false
		muzzle.scale.y = 1
	
	if Input.is_action_just_pressed("fire"):
		var bullet_instance = FIREBALL.instantiate()
		get_tree().root.add_child(bullet_instance)
		bullet_instance.global_position = muzzle.global_position
		bullet_instance.rotation = rotation

#fireball.gd (any projectile for now)

extends Node2D

var SPEED = 500
var damage = 10
	
func do_tragectory(delta: float) -> void:
	position += transform.x * SPEED * delta 
	
func _process(delta: float) -> void:
	do_tragectory(delta)

Weapon Scene:

Try positioning it before adding it as a child of root

var bullet_instance = FIREBALL.instantiate()
bullet_instance.global_position = muzzle.global_position
bullet_instance.rotation = rotation
get_tree().root.add_child(bullet_instance)

That’s at least how i’d do it

Little side note.
I’d use

get_tree().current_scene

instead of

get_tree().root

So this should hopefully fix your issue

var bullet_instance = FIREBALL.instantiate()
bullet_instance.global_position = muzzle.global_position
bullet_instance.rotation = rotation
get_tree().current_scene.add_child(bullet_instance)
2 Likes

Thank you!

1 Like