Filter rotation without Slerp

Hi!

I’d like to filter the compass heading value to have a smooth rotation, but using Slerp causes too much lag.

I tried to implement a manual filter using an Alpha value, but the problem in this case is that when passing from 359 deg to 0, the view does a full 360 degrees rotation, and this is obviously not what I want.
The filter I wrote is this:
float filteredHeading = (m_Alpha * m_OldHeading) + ((1 - m_Alpha) * heading); m_OldHeading = filteredHeading;

Is there a way to filter the rotation without a smoothing of the Slerp function and without the “jump” of the manual filter?

Thanks in advance and have a nice day!

The following code will use SmoothDamp for smooth rotation and is frame independent (I only have the script for C#):

public static Vector4 ToVector4 (this Quaternion quaternion) {
	return new Vector4 (quaternion.x, quaternion.y, quaternion.z, quaternion.w);
}

public static Quaternion ToQuaternion (this Vector4 vector) {
	return new Quaternion (vector.x, vector.y, vector.z, vector.w);
}

public static Vector4 SmoothDamp (Vector4 current, Vector4 target, ref Vector4 currentVelocity, float smoothTime) {
	float x = Mathf.SmoothDamp (current.x, target.x, ref currentVelocity.x, smoothTime);
	float y = Mathf.SmoothDamp (current.y, target.y, ref currentVelocity.y, smoothTime);
	float z = Mathf.SmoothDamp (current.z, target.z, ref currentVelocity.z, smoothTime);
	float w = Mathf.SmoothDamp (current.w, target.w, ref currentVelocity.w, smoothTime);

	return new Vector4 (x, y, z, w);
}

public static Quaternion SmoothDamp (Quaternion current, Quaternion target, ref Vector4 currentVelocity, float smoothTime) {
	Vector4 smooth = SmoothDamp (current.ToVector4 (), target.ToVector4 (), ref currentVelocity, smoothTime);
	return smooth.ToQuaternion ();
}

How to use it:

private Quaternion currentRotation; // The current rotation
private Quaternion targetRotation; // The rotation it is going towards
private float rotationV; // Current rotation velocity
private float smoothTime = 0.5f; // Smooth value between 0 and 1

void Start () {
	// Set currentRotation and targetRotation
	currentRotation = transform.position;
	targetRotation = someValue;
}

void Update () {
	currentRotation = SmoothDamp (currentRotation, targetRotation, ref rotationV, smoothTime); // Smoothly change the currentRotation towards the value of targetRotation
	
	transform.rotation = currentRotation; // Or whatever it is you are trying to rotate
}