turn pistol with body in godot

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

I have a problem…

I have a 2D game with guns and stuff (pokemon 2D style not top down) and i have the problem that my body dont turns in the direction my gun is shooting at.

For the Player I have a normal Kinematic body and For the bullets I have an area that turns with mouse_position ( look_at(get_global_mouse_position)) )
And my Player only have animations for north, east, south and west…

Is it possible to shoot in the direction my character is looking at ( east, west, south or nord) ?

:bust_in_silhouette: Reply From: Geazas

Is this what you want to try to achieve? Imgur: The magic of the Internet

If it’s the case, you can measure the angle between player and mouse to determine which way they are facing. Then set the animation accordingly

func _process(delta):
	var angle_to_mouse = global_position.angle_to_point(get_global_mouse_position())
	angle_to_mouse = rad2deg(angle_to_mouse)
	angle_to_mouse = wrapf(angle_to_mouse, 0, 360)

	if angle_to_mouse < 45 or angle_to_mouse >= 315:
		animation = "left"
	elif angle_to_mouse >= 45 and angle_to_mouse < 135:
		animation = "up"
	elif angle_to_mouse >= 135 and angle_to_mouse < 225:
		animation = "right"
	else:
		animation = "down"

Then for the bullet, you can check which direction the character is facing, and set the direction vector to the bullet on instancing it.

func shoot():
	var bullet = bullet_scene.instance()
	bullet.global_position = global_position
	match animation:
		"left":
			bullet.dir = Vector2.LEFT
		"right":
			bullet.dir = Vector2.RIGHT
		"down":
			bullet.dir = Vector2.DOWN
		"up":
			bullet.dir = Vector2.UP
	get_tree().current_scene.add_child(bullet)

And here’s the bullet script

extends Sprite

var dir: Vector2

func _physics_process(delta):
	position += dir * 10