Issues rotating mesh in direction of movement

Godot Version

Godot 4.3

Question

I am attempting to rotate a mesh in the direction it is moving, but no matter what I try, I can not get it to work properly. I have been using the “lerp_angle()” method, but am struggling to figure out what the second input should be. This is all potentially relevant parts of the script I am using.

func _physics_process(delta):
	var input_dir = Input.get_vector("move_left", "move_right", "move_forward", "move_backward")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	var relativeDir = Vector3(input_dir.x, 0.0, input_dir.y).rotated(Vector3.UP, cameraArm.rotation.y)
	if direction:
		lastDir = relativeDir
		velocity.x = relativeDir.x * SPEED
		velocity.z = relativeDir.z * SPEED
		
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)
		
	move_and_slide()
	
	model.rotation.y = lerp_angle(model.rotation.y, (?), delta * 12)

if your rotation doesn’t change then the angle of the input_dir should be your target rotation

model.rotation.y = lerp_angle(model.rotation.y, input_dir.angle(), delta * 12)

I added in the “input_dir.angle()” as suggested, but am still faced by some issues. As is, the script would make the mesh’s rotation equal to zero when there was no input. This was fixed by wrapping the line in this if condition, but there are still an issue: the rotation stops abruptly if the input is released during the rotation. How could I fix this?

The edited code as is:

if input_dir.angle() !=0 or Input.is_action_pressed("move_right"):
		model.rotation.y = lerp_angle(model.rotation.y, input_dir.angle() * -1, delta * 12)

Maybe you could use the angle of the velocity, flattened

var planar_velocity := Vector2(velocity.x, velocity.z)
if not planar_velocity.is_zero_approx():
    model.rotation.y = lerp_angle(model.rotation.y, planar_velocity.angle(), delta * 12)

Unfortunately, that doesn’t seem to have worked. Is it possible to make sure that the lerp_angle() method does not stop abruptly?

“lerp” is “linear interpolate”, so it’s going to stop abruptly. The usual fix for this is easing.

That link should jump to the docs for ease().

1 Like

I was able to fix it after doing a bit of research. Here is what I found to work if anyone needs it:

model.rotation.y = lerp_angle(model.rotation.y, atan2(-lastDir.x, -lastDir.z), delta * 12)```

What is different about that line from this one? keep in mind that .angle() is short for atan2 on the vector’s components.