Snake clone, need help with sprite facing correct direction

Godot Version

Godot 4

Question

Hi, I am trying to make a clone of a classic top-down snake game. So far, I have a CharacterBody2D that moves and flips when I move left or right. However, I want the sprite to move to face up and down when the player moves it in those directions. How would I go about that? Would I use an animation player? I am somewhat new to programming, and I’m trying to do more than just follow a tutorial mindlessly. I will post my Player script below. Any advice would be appreciated, thanks!

extends CharacterBody2D

# speed in pixels/sec
var speed = 500 

func _physics_process(_delta):
# setup direction of movement
	var direction = Input.get_vector("left", "right", "up", "down")
# stop diagonal movement by listening for input then setting axis to zero
	if Input.is_action_pressed("right") || Input.is_action_pressed("left"):
		direction.y = 0
	elif Input.is_action_pressed("up") || Input.is_action_pressed("down"):
		direction.x = 0
	else:
		direction = Vector2.ZERO
		
#flip the sprite based on left/right direction
	if Input.is_action_pressed("right"):
		$Sprite2D.flip_h = true
	else: if Input.is_action_pressed("left"):
		$Sprite2D.flip_h = false
	
#normalize the directional movement
	direction = direction.normalized()
# setup the actual movement
	velocity = (direction * speed)
	move_and_slide()

class_sprite2d: Sprite2D — Godot Engine (stable) documentation in English

You are already using flip_h.
There is still flip_v: If true, texture is flipped vertically.


I am somewhat new to programming,

#flip the sprite based on left/right direction
Do you already understand what happens with “left / right”, can you expand it yourself for “up / down”?

1 Like

Are you saying I’d use the same code but change it to flip_v? I think I can handle that on my own, I didn’t realize it would work like that too. Now that I’m thinking about it, I’m pretty sure I’ve just jumped the gun in asking on here and I could have figured it out on my own. Thank you for the push in the correct direction though!

1 Like

Of course, your assets have to fit for flip_v.

If not, try: AnimatedSprite2D — Godot Engine (stable) documentation in English

Godot 3.2 RPG Example (top-down)

onready var anim : AnimatedSprite = $AnimatedSprite

func manage_animation():
	
	if vel.x > 0: play_animation("MoveRight")
	elif vel.x < 0: play_animation("MoveLeft")
	elif vel.y > 0: play_animation("MoveDown")
	elif vel.y < 0: play_animation("MoveUp")
	elif facingDir.x == 1: play_animation("IdleRight")
	elif facingDir.x == -1: play_animation("IdleLeft")
	elif facingDir.y == 1: play_animation("IdleDown")
	elif facingDir.y == -1: play_animation("IdleUp")
		
	pass

func play_animation(anim_name):
	
	if anim.animation != anim_name:
		anim.play(anim_name)
	
	pass