How to make a gun that rotates according to the mouse?

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

This question has been asked ALOT, but when I do this from other answers, I get the gun moving far away from the mouse(if this qa page had video inserting, I could give you better description) It is moving real round, and further away from it’s original position. What I need is the gun to not be able to move outside of the center/position it is given, and can also move according to the mouse. Please answer…

Could you at least tell us if this is a 2D game or a 3D game?

Ertain | 2021-01-27 17:45

Agreed 2D or 3D?

Wakatta | 2021-01-28 01:38

:bust_in_silhouette: Reply From: Surtarso
func _physics_process(_delta):
	look_at(get_global_mouse_position()) #rotate to mouse position

func _input(event):
	if event is InputEventMouseMotion: _set_aim() #sets aim distance

func _set_aim(): #sets aim distance to player
	var player_position: Vector2 = (self.global_position - global_position).normalized()
	var player_to_cursor: Vector2 = get_local_mouse_position() - player_position
	var aim_direction: Vector2 = player_to_cursor.normalized()
	var cursor_vector: Vector2 = aim_direction * aim_distance
	var final_position: Vector2 = player_position + cursor_vector
	$AimSprite.position = final_position #places aim