How to spawn bullet in given direction [Possible duplicate, but other answer does not work]

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

Edit: Correct solution at the post’s end. Original question here:

I’m trying to spawn a bullet and apply impulse to it in a given direction. This is how the direction is given:

Setup

Imgur: The magic of the Internet #Image above is not loading so just in case.

I have a Marker2d as a child of the player, and a Sprite as it’s child, positioned around 30px ahead of it (Positioned, not offset, since that will cause global_position confusion around the code)

So upon button press and holding of this button, the sprite will rotate around the player (By rotating the Marker2d Node), and when released it should shoot a bullet in the sprite direction.

So after searching around and stumbling upon the code from this post , this is the code so far:

func _on_shoot_released():
	get_tree().call_group("player", "shoot", sprdir.global_position, sprdir.rotation)

I have a separete Scene Tree for the HUD/Controls that’s why I call group like this, sending the sprite’s current position and rotation.

On the Player side:

func atirar(pos, rot):
	var bullet:RigidBody2D = itens[0].instantiate()
	bullet.global_position = pos
	var impulse:Vector2 = Vector2(cos(rot), sin(rot))
	bullet.start(impulse)
	cena_pai.add_child(bullet)

And the bullet itself:

func start(impulse):
	apply_central_impulse(impulse  * 100)

The problem is that the bullet always goes right on the screen, does not really follow the sprite’s position/direction. What am I missing here?

SOLUTION:

As pointed out by @Gluon down here, godot has a built-in function for direction, direction_to. However I could not use it since Sprite2D does not inherit it, BUT, the doc itself states that it’s simply a mater of one position minus the other, therefore the working code is:

func atirar(pos):
	var dir = ($DirItem.global_position - global_position) #Have to get rid of the $ call here
	var bullet:RigidBody2D = itens[0].instantiate()
	bullet.global_position = pos #Still needs a tweak here but it's failry easy
	bullet.start(dir)
	cena_pai.add_child(bullet)

Normalize it or don’t, depends on your case.

1 Like
:bust_in_silhouette: Reply From: Gluon

You can use direction_to in order to get the correct direction. More details are on the godot website here

Thanks for your answer, sometimes it’s the simplest solution right? I may be overthinking. But the problem is, I can’t use direction_to on a Sprite unfortunelly.

BUT thanks to you I got the answer from the docs =D. Thank you, I’ll choose your answer as the right one but I’ll update the code in the main question with the correct answer.

luiscesjr | 2022-11-30 11:33

Glad you got the answer, good luck with your game!

Gluon | 2022-11-30 15:42