Hi, I’m wondering how I can slowly rotate the player towards my mouse position in 3d so that the speed of the rotation can be changed.
I would recommend doing the following:
// Get the direction towards the mouse position
Vector3 direction = mousePosition - playerTransform.position;
// Get the rotation the player has to have to be looking directly at the mouse position
Quaternion desiredRotation = LookRotation(direction);
// Interpolate the player's rotation towards the desired rotation
playerTransform.rotation = Slerp(playerTransform.rotation, desiredRotation, rotationMultiplier * Time.deltaTime);
By using this approach, the player’s rotation towards the mouse position will be quite smooth. The rotation speed will become progressively slower as the player gets closer to looking straight at the mouse position.
*
You could also try using the method “Vector3.RotateTowards()” to get a Vector3 direction that is rotated slightly towards the mouse position. Then use “Quaternion.LookRotation()” to rotate the player towards this new direction. If this sounds confusing, there is a great example on the “Vector3.RotateTowards()”'s documentation page. Use this if you want the speed of the rotation to be constant (though you can also make this smooth, if you again use interpolation).
*
Alternatively (though more cumbersome), you could create an empty GameObject that uses the method “Transform.LookAt()” to constantly look at the mouse position. Then you could interpolate (using “Quaternion.Slerp()”) the player’s rotation towards the GameObjects rotation. This should also result in a smooth rotation motion.
*
Links to documentation for the mentioned methods:
Vector3.RotateTowards() - Unity - Scripting API: Vector3.RotateTowards
Quaternion.LookRotation() - Unity - Scripting API: Quaternion.LookRotation
Transform.LookAt() - Unity - Scripting API: Transform.LookAt
Quaternion.Slerp() - Unity - Scripting API: Quaternion.Slerp
*
I haven’t tested the code, but it should (hopefully) work. Hope it helps!