How do you flip sprites based off of rotation?

v4.2.2.

Video

Question

Basically, when I aim my character’s gun, I want the arm sprite to flip horizontally when it passes the half way line (so imagine a vertical line through the center of a circle).

Code

sprite is the actual character sprite
gun is the spite for the arm and gun, the one that rotates
pivot is the pivot that is placed on the character (sprite)'s shoulder that the gun rotates around

extends CharacterBody2D

var direction: Vector2 = Vector2.ZERO
var gun_aim: Vector2 = Vector2.ZERO
var last_direction: Vector2 = Vector2.RIGHT
var is_rolling: bool = false
var can_flip: bool = true
@export var speed: int = 75
@onready var anim_player = $AnimationPlayer
@onready var sprite = $Sprite2D
@onready var pivot = $"Shoulder Pivot"
@onready var gun = $Gun

func _process(delta):
	if Input.is_action_pressed("p1attackA"):
		anim_player.play("cowboyAim")
		speed = 0
		can_flip = false
		gun_aim = Input.get_vector("p1aimLeft", "p1aimRight", "p1aimUp", "p1aimDown").normalized()
		if gun_aim.length() > 0:
			if sprite.flip_h:
				var angle = atan2(-gun_aim.y, -gun_aim. x)
				pivot.rotation = angle
			else:
				var angle = atan2(gun_aim.y, gun_aim.x)
				pivot.rotation = angle
	else:
		pivot.rotation = 0
	
	if Input.is_action_just_released("p1attackA"):
		speed = 75
		can_flip = true

func _physics_process(delta):
	velocity = direction * speed
	move_and_slide()

I assume that at 0 rotation, the arm is pointing right? In that case, you will flip the arm sprite when the pivot’s rotation is greater than PI / 2 rad or 90 degrees, or less than - PI / 2 rad or -90 degrees.

I can’t find anything in the docs that demonstrates the rotation, so I made this:

I hope it helps!

1 Like

I’ll see if I can make sense of this, thanks.