Continously correct rotation

I’m trying to continously correct the rotation of an object.
Imagine a spaceship. When the spaceship collides on a side it rotates and then automatically rotates again to be “flat” again.

I tried things like this

function Update(){
var newRotation = Quaternion.AngleAxis(0, Vector3.up);

transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, Time.deltaTime * 2.0f * 10);


and the same using Slerp.

For both the object starts jittering fast.

How can archieve this correction over time smoothly? Should I change the approach? I’m doing something wrong in the current code?

Any suggestion is welcome

Thank you.

If you are using physics, you can try relative torque towards the flat angle, similar to how a pilot would use side thrusters to stabilise. i.e. complex mix of non linear relative torque levels relative to rotation angle, and some if conditions.

to get rid of jitter, you should switch off the physics at any time that you are rotating manually the rotation variables…
do that by changing the rotation velocity Unity - Scripting API: Rigidbody.angularVelocity

you can change it slowly relative to time, and you can change the drag coefficient too while stabilising if it makes the craft more responsive, it can be like invisible thrusters increasing drag.

If it is the physics engine that gives the jittering, you could temporarily disable the physics (fx Rigidbody or BoxCollider or whatever) component on your object, just while you make the animation as originally posted.

And then reenable those same components when all is back in place, and the game continues.

Code examples on enable/disable:

Thanks for the answers. I can’t upvote for having little reputation.

Disabling the physics is not an option because I need to always detect collisions. At the end I’m using physics and creating torque to the object under some conditions.

Here’s some code:

if(transform.rotation.eulerAngles.z > 0+rotationThreshold && transform.rotation.eulerAngles.z < 180)
		rigidbody.AddRelativeTorque(-transform.forward * autoBalanceForce * transform.rotation.eulerAngles.z);
if(transform.rotation.eulerAngles.z >= 180 && transform.rotation.eulerAngles.z < 359-rotationThreshold)
		rigidbody.AddRelativeTorque(transform.forward * autoBalanceForce * -(transform.rotation.eulerAngles.z-360));

I’m doing this for every axis.

It REALLY helped increasing the angular drag of the rigidbody, so it stops bouncing side to side in little time.

I think I can consider this as resolved. Do I have to do anything in special?

See you around