Search code examples
3drotationgodot4

Imitating an object's rotation in Godot 4 after they turn 180° in any direction


I am new to Godot 4, I am transferring from Unity. In my game the player controls a spaceship, which is followed by a camera. After getting the input, I update the player's velocity and rotation. However, I do not like when the camera mirrors exactly the player's rotation so I added a lerp in the player's script to control the camera's rotation. The player setup looks like this:

Player
   Marker3D
       Camera

And the lines of code in the player's script that move and rotate the camera:

Marker3D.position = Marker3D.position.lerp(playerbody.position,.5)
Marker3D.rotation = Marker3D.rotation.lerp(playerbody.rotation,.3)

This works great to make the camera follow the player, except when the player turns 180° in any direction, when the camera jumps to the current player's current rotation instead of smoothly transitioning. Is there any way to fix this? Thanks!


Solution

  • Ok, I found the problem. I was accessing the rotation directly instead of using quaternions. The code below uses quaternions and fixes the issue:

    var a = Quaternion(playerbody.transform.basis)
    var b = Quaternion(Marker3D.transform.basis)
    var c = b.slerp(a,0.3)
    Marker3D.transform.basis = Basis(c)