Calculating the difference between forward direction and velocity direction to set the body roll of my vehicle.

Hi all,

As a relatively new Unity developer I’m having trouble coming up with a solution, possibly due to my vague understanding of the relationship between quaternions and euler angles.

Adding body roll to the model of my vehicle by calculating the difference in y angle between the angle the vehicle is facing and the direction of velocity/momentum. By adding it to the model instead of the parent/controlling object I was hoping to avoid over-complicating the steering process.

Currently my pseudo-code for this: (Code at its most basic level, disregarding euler to quaternion.)

rollAngle = ( parent.forward.y - parent.rigidbody.velocity.y ) / 2; 

transform.eulerAngle = new Vector3 (0, 0, rollAngle);

Should mean that when the direction of the vehicle is perpendicular to its momentum on the y-axis it will produce a 45 degree body roll.

So to sum up, I’m looking to take the y rotation of my object and subtract the y rotation of its velocity divide the value by two and then use it to add body roll to my object on the z axis. I think I need to convert both to eulerAngles and subtract them that way, but I haven’t yet discovered a way to do so.

Thanks for taking the time to help me out!

Your code looks like its does ALMOST exactly this:
"To to sum up, I’m looking to take the y rotation of my object and subtract the y rotation of its velocity divide the value by two and then use it to add body roll to my object on the z axis. "

With the one exception: you are REPLACING the rotation of the object with this, rather than adding to it.

 transform.eulerAngle = new Vector3 (0, 0, rollAngle);

If you wish to rotate the existing orientation, by that angle try something likethis:

 transform.rotation = transform.rotation * Quaternion.Euler(0, 0, rollAngle);  

(it uses this operator to combine the rotatations: Unity - Scripting API: Quaternion.operator *)

Edit: note-the above operator “adds” the second Quaternion to the First. If you wish to reverse the rotation of the second Quaternion to do a “subtraction”, use Unity - Scripting API: Quaternion.Inverse ,like so:

 transform.rotation = transform.rotation * Quaternion.Inverse(Quaternion.Euler(0, 0, rollAngle));  

(silly in this case, because you could have just used rollAngle * -1 to begin with)