Godot Version
4.2.2
Question
Working code - I have BlueBasicEnemy fires homing projectiles at the player. Works great. Code below:
extends CharacterBody2D
var t: float = 0.0
@onready var BLUE_BASIC_PROJ = preload("res://scenes/blue_basic_proj.tscn")
@onready var main_game = $"../.."
@onready var ship = $"../../ship"
@onready var bb_1 = $"."
# Fire at Player
func _process(delta: float) -> void:
t += delta
if t >= 1.0:
t -= 1.0
attack_homing()
func attack_homing():
var projectile = BLUE_BASIC_PROJ.instantiate()
main_game.add_child(projectile)
projectile.position = position
if bb_1:
projectile.launch(ship)
And here’s the projectile code:
extends Area2D
const MOVE_SPEED = 300
const STEER_FORCE = 100
var velocity = Vector2.ZERO
var acceleration = Vector2.ZERO
var target = null
@onready var bb_1 = preload("res://scenes/BlueBasicEnemy.tscn").instantiate()
@onready var shipcall = preload("res://scenes/ship.tscn").instantiate()
func seek():
var steer = Vector2.UP
if target:
var desired = (target.position - position).normalized() * MOVE_SPEED
steer = (desired - velocity).normalized() * STEER_FORCE
return steer
func _physics_process(delta):
acceleration = seek()
velocity += acceleration * delta
position += velocity * delta
func launch(target):
self.target = target
func _on_body_entered(_body):
Globals.HitBy = "blue"
Globals.ReflectTarget = bb_1
queue_free()
shipcall.impact()
^ This all works. I have the ship firing back when hit, this is the part not working and I think(?) it’s a tree issue but I’m too inexperienced at this.
Ship code (not working): (collision calls the reflect func, that’s all good)
extends CharacterBody2D
const SPEED = 400.0
const REFLECT_PROJ = preload("res://scenes/reflect_proj.tscn")
@onready var MAIN_GAME = $".."
@onready var bb_1 = $"../Enemies/BB1"
func reflect():
var projectile = REFLECT_PROJ.instantiate()
MAIN_GAME.addchild(projectile)
projectile.global_position = self.global_position
projectile.launch(bb_1)
I get “Invalid call. Nonexistent function ‘addchild’ in base ‘Nil’.”
If I @onready the REFLECT_PROJ instead of const, I get a similar error there.
Here’s my tree:
My inexperience is kicking my butt. Let me know if I can clarify anything.