How to have CharacterBody2D maintain rotation angle after input stops?

Godot Version

Godot 4.5 Stable

Question

I’m currently working on player physics for a top-down 2D project in Godot 4.5. I’ve managed to get the character to rotate to the direction of input but upon letting go of WASD keys the direction the player faces returns to the right. I’d like for the player to remain facing the angle it’s at when input stops, since this is a true birds eye view I am using only 1 sprite for all angles and would just like it to rotate. I’m incredibly new to Godot and programming in general, and none of the resources I’ve found solve this issue, nor have I been able to figure this out with the documentation. I apologize if this is a novice question!

My code is as follows:

extends CharacterBody2D

@export var max_speed : float = 150
var sprint_speed : float = 350
var last_direction = Vector2.ZERO
var current_direction = Vector2.ZERO
var initial_position = Vector2.ZERO
var percent_to_next_position = 0.0

func _physics_process(_delta):
	# Get input direction
	var input_direction = Input.get_vector("left", "right", "up", "down")
	velocity = input_direction * max_speed
	move_and_slide()
	
	var collision_detected: bool = move_and_slide()
	if collision_detected:
		print("Collision occurred!")
	
	# move and slide function
	
	#  ROTATE THAT thing !
	rotation = lerp_angle(rotation,velocity.angle(),0.1)

It’d be a good idea to get the debugger or add print() to this code, comparing what value you think the lines produce, to what value is actually there. You basically do .angle() on a zero no-input vector which makes no sense, and the 0 it gives you back is not usable.

Don’t rotate the character if the velocity has a length of 0.

1 Like

You could add an if statement to avoid rotating unless a condition is met, such as non-zero input direction

if input_direction:
	#  ROTATE THAT thing !
	rotation = lerp_angle(rotation,velocity.angle(),0.1)
1 Like