How can I make a mesh face the direction it is moving in?

Godot Version

4.3

Question

I am trying to make the mesh of the player rotate in the direction that the player is moving. Right now I just have the basic 3d movement template script. Hopefully I can just use the code in the template to make this.

Code:

extends CharacterBody3D


const SPEED = 5.0
const JUMP_VELOCITY = 4.5


func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity += get_gravity() * delta

	if Input.is_action_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	var input_dir := Input.get_vector("left", "right", "forward", "backward")
	var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()

You could use the angle of the input_dir as the mesh’s rotation.y. Make sure to only rotate the mesh as rotating the CharacterBody3D will also rotate the input/direction.

var input_dir := Input.get_vector("left", "right", "forward", "backward")
$Mesh.rotation.y = input_dir.angle()

This almost works great! the only thing is when moving forward and backward the angle is mirrored. I’m not sure how fix that without messing up the left and right. Any ideas?

You could add a parent Node3D to your mesh and rotate that instead, allowing you to make adjustments to the mesh’s rotation. Negative Z is facing “forward” in Godot.