Flipping Sprite Around

Godot Version

Ver 4.1.1

Question

I’m still a beginner at this and am learning my way around GDScript and the like. I’ve gotten most movement down but the one thing that alludes me is getting my character to turn around when moving in that direction. It’s a 2D game and my movement code looks like this:

extends CharacterBody2D

@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
var animation_locked: bool = false
var direction: Vector2 = Vector2.ZERO

func _physics_process(delta):
direction = Input.get_vector(“A”, “D”, “W”, “S”)

velocity = direction * 400
move_and_slide()
if velocity.length() > 0.0:
	animated_sprite.play("walk")
else: 
	animated_sprite.stop()

The character by default faces the right and none of the other posts or videos I found seem to work quite right with this. I know I need to trigger flip_h but I can’t figure out how, Input.is_action_pressed wasn’t working for me, nor was using the direction, but I could’ve easily just done it wrong.

Check the direction you are going and set the AnimatedSprite2D.flip_h accordingly

if direction.x < 0:
	animated_sprite.flip_h = true
elif direction.x > 0:
	animated_sprite.flip_h = false
1 Like

That worked, thank you! I tried something like that earlier but it looks like putting it in a separate function in the script from the physics function messed it up.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.