Defining the rotation of a transform to rotate an object via Lerp

Ok, so I’m trying to get an object to rotate 180 degrees after a keystroke triggers a gravity reversal in my game (so that it’s “walking on the ceiling”, or back on the ground after a second reversal). I’ve got the gravity part worked out but I’m having trouble getting the object to rotate when the gravity shift occurs.

I’ve searched all over for a few hours now on how to Lerp between the two rotations and most answers provide something like this:

transform.rotation = Quaternion.Lerp (fromRotation, toRotation, Time.time * speed);

with fromRotation and toRotation being Transforms. But nothing explains how I define those Transforms other than to have an empty variable to drag in objects (but the unity scripting reference says they should be different objects than the one my script is attached to- which doesn’t help me at all since all three of these things (the current rotation, the destination rotation and the object this script is attached to) are all applying to the same object).

So how do I define the toRotation to simply be 180 degrees from the fromRotation/current rotation in the first place? i know Quaternions aren’t simply x/y/z but I’m not seeing how to define a rotation without making extra objects for them to look at (which I could do, I suppose, but that’s seems extraordinarily unnecessary).

First, you rotation code as you have listed it will not work. The typical use is:

transform.rotation = Quaternion.Lerp (transform.rotation, toRotation, Time.deltaTime * speed);  

This will produce an eased rotation (slower at the end). It is by far the most commonly posted Quaternion.Lerp() code on Unity Answers, but is an “misuse” of Lerp(). The last value of Lerp() is designed to increment from 0 to 1. This is often done by using a timer, and the result is a linear movement without the easing at the end.

As for creating quaternions, there are several functions in the Quaternion class that will create them for you. For example Quaternion.Euler() will produce a rotation with a specified angle:

var qTo = Quaternion.Euler(180, 0, 0);

Note quaternions are not the only way to solve your problem. You could use Transform.Rotate() for example or you could assign angles directly to Transform.eulerAngles. As with most things concerning rotations, are some gotchas with these two solutions as well.