How to make the Direction of randomly spawned bullets, the same as their random Sprite rotation?

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

The spawn position is the same for every bullet.

:bust_in_silhouette: Reply From: Magso

Spawn the bullets as children of the sprites and use

set_global_rotation(get_parent().get_global_rotation())

Note that the question asked about movement direction - they’ve already set the rotation.

In addition, this answer demonstrates bad coding practices. Don’t use set_global_rotation(), use the global_rotation property. Also, you should avoid using get_parent() as it breaks if you change tree location - objects should not reference nodes above them in the tree.

kidscancode | 2019-05-08 17:08

Ah, I thought by direction they meant rotation and coded from the bullet.
Also unless the hierarchy is constantly changing, I would’ve thought get_parent() is ok for a one time reference if the new instance has a script of its own. I get how it could get messy if it’s used too regularly.

Magso | 2019-05-08 18:01

:bust_in_silhouette: Reply From: kidscancode

If I understand your question correctly, you’ve chosen a random rotation for the bullet, and you want it to travel in the chosen direction.

Assuming you have a velocity vector for movement:

velocity = Vector2(speed, 0).rotated(rotation)

Or you can use the bullet’s transform, which gives you its forward vector:

velocity = transform.x * speed

You didn’t mention what kind of node the bullet is or how you’re moving it, so you’ll have to adapt to whatever your movement scheme is.