Random spinning using while using lerp

Godot Version

3.6

Question

Hey guys! I am trying to develop this project where the character is controlled entirely by a mouse. I got the movements done but I can’t figure out how I could make the “Prototype player cube” turn towards the direction it is move towards smoothly. As you can see, the cube randomly rotates sometimes. How do I fix it? Too bad I couldn’t upload files here… Maybe try this link

And here’s the code:

extends KinematicBody

var mousepos:Vector2
var difference
var speed = 1
var velocity
func _ready():
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)


func _input(event):
	
	var direction = Vector3.ZERO
	if event is InputEventMouseMotion:
		direction.x += event.relative.x
		direction.z += event.relative.y
	velocity = direction
	move_and_slide(velocity)
	if velocity != Vector3.ZERO:
		var lookdir = atan2(-velocity.x, -velocity.z)
		rotation.y = lerp(rotation.y, lookdir, 0.25)

Lemme know if you guys want any additional context! I really appreciate your help!

Use lerp_angle when interpolating angle values. @GlobalScope — Godot Engine (stable) documentation in English

1 Like

Yeah, thanks man! That worked!