How do i make the bat spawn projectiles?

Godot Version

gd4

Question

i want to make the bats able to spawn projectiles whenever it gets hit. the following screenshot is what the rough idea of what im trying to make here

you dont need to tell me a way on the trajectory, i could try figuring it out myself. but im stuck with trying to spawn the projectiles in the first place. (the projectile in the screenshot is an object i added manually into the world)

The first step is letting the bat know where the projectile scene is, this can be done with @export and/or preload

@export var projectile_prefab: PackedScene
# or
const projectile_prefab = preload("res://my_projectile.tscn")

Now when the time is right, we instantiate the scene and add it as a child to an appropriate node, a good first attempt would be either the tree root or as a sibiling of the bat. We must also set it’s position to match the bat’s position, any other special properties should be applied too.

func _on_timer_timeout() -> void:
    var clone = projectile_prefab.instantiate()
    clone.position = self.position
    add_sibling(clone)

And there you have it! Make sure to free the projectiles if they don’t hit anything, the VisibleOnScreenNotifier is good for cleaning up such things.

1 Like

thank you! it worked!

1 Like

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