How to shoot from a rotated gun

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By alienbeliever
:warning: Old Version Published before Godot 3 was released.

Gathering from different sources, I found the solution. Hope it helps.
NOTE: Bullet is a “RigidBody2d”, and gun is a “Sprite
func bullet():
var rot = get_rot() #rotation
var vel = 300 #Bullet’s velocity
var dir = Vector2(sin(rot), cos(rot)) #direction
var dis_origin = 50 #distance from origin, you can set this to your own liking
var spawn_point = get_global_pos() + dir * dis_origin
var bullet = preload(“res://scenes/bullet.tscn”).instance()
bullet.set_global_pos(spawn_point)
bullet.set_linear_velocity(Vector2(0, vel).rotated(rot))
get_tree().get_root().add_child(bullet)
pass

alienbeliever | 2017-04-16 12:19

:bust_in_silhouette: Reply From: DodoIta

You could use a Position2D node as a child of the gun.
You place it near the muzzle (or wherever you want) via the inspector, then in the script you get its position and instance bullets there.
That way it rotates according to the rotation of the gun and it’s much simpler and more readable :slight_smile: