Godot Version
Godot 4.7.2
Question
I’m new to godot (this is my second project) and I’m trying to make a projectile for my game, however the projectiles keep spawning at (0,0), I know this is because the _ready() is running after the instantiate, however I don’t know why this is happening and I’m not sure how to fix it. Could someone please explain why this is happening so I can avoid it in the future, as well as a fix/work around. Thank you!
#Projectile Code:
extends CharacterBody2D
@export var SPEED = 100
var dir: float
var spawnLoc: Vector2
var spawnDir: float
func _ready():
print("here")
spawnLoc = get_global_position()
spawnDir = get_global_rotation()
print(spawnLoc)
print(spawnDir)
func _physics_process(delta):
velocity = Vector2(0, -SPEED).rotated(spawnDir)
move_and_slide()
#Player Code:
extends CharacterBody2D
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
@onready var game = get_tree().root.get_node("Game")
@onready var projectile = preload("res://scenes/projectile.tscn")
func shoot() -> void:
#var projectile = preload("res://scenes/projectile.tscn")
var instance = projectile.instantiate()
game.add_child.call_deferred(instance)
instance.dir = rotation
instance.spawnLoc = get_global_position()
instance.spawnDir = get_global_rotation()
print("here2")
print(instance.spawnLoc)
print(instance.spawnDir)
func _physics_process(delta: float) -> void:
# Add the gravity.
var directionX := Input.get_axis("left", "right")
if directionX:
velocity.x = directionX * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
var directionY := Input.get_axis("up", "down")
if directionY:
velocity.y = directionY * SPEED
else:
velocity.y = move_toward(velocity.y, 0, SPEED)
if Input.is_action_pressed("shoot"):
shoot()
move_and_slide()