How to add shooting to my 2d game

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SoMir

Hi, this is my first post here so I don’t know if I put this in the right category.

However, I’m trying to create a cube bullet(Which is a scene) when I press some button.
I created this function, but it doesn’t work, nothing happens. What am I doing wrong?

onready var bullet = preload("res://Bullet.tscn")

func Shoot():
var bull = bullet.instance()
bull.position = position
bull.apply_impulse(Vector2(0, 0), Vector2(15, -15))
yield(get_tree().create_timer(4.0), "timeout")
bull.queue_free()
:bust_in_silhouette: Reply From: kidscancode

You’re not adding your new bullet instance to the scene tree. Use add_child(bull) after instancing it.

Note: adding the bullet as the child of the node that’s instancing it may not be what you want. For example, if the player instances the bullet, you don’t want the bullet to be a child of the player, because then it will be “attached” to the player’s movement/rotation. You probably want to make it a child of the scene root, in which case you can use owner.add_child(bull). You might also need to use bull.position = global_position depending on how things are arranged in your scene.

Also, does the bullet have a script on it? If so, it’s probably better to have the bullet keep its timer and remove itself, rather than suspending so many Shoot() functions.

Thank you so much! I did exactly that and it worked. My bullet didn’t have a script attached, but I was planning to add it, so I made this function inside:

func die():
yield(get_tree().create_timer(4.0), "timeout")
queue_free()

And I’m just calling it in my shoot function. Thanks once again!

SoMir | 2020-07-12 07:24