Set angle of object around arbitrary axis by slider?

Here’s the situation: my object needs to rotate a defined angle around an arbitrary axis I calculated between two Vector3’s. The angle is controlled by a GUI.HorizontalSlider.

For example, if I move my slider 4 to the left, my object needs to rotate by 4° around my axis.
I tried to use transform.RotateAround but then my rotation never stops and I only control the rotation speed with my slider:

angleSlider = GUI.HorizontalSlider (new Rect (5,103,165,20), angleSlider, -7f, 7f);
myObject.transform.RotateAround(myObject.abutment.transform.position, ax, angleSlider);

angle around an arbitrary axis

Today is your lucky day, because that’s actually how Unity represents all rotations internally: quaternions!

Skipping a bunch of crazy math about imaginary numbers (which you can read about around the net), quaternions are relatively easy to define based on two things:

  • An axis
  • Rotation around that axis

We call that angle-axis representation.

Assuming you already have those values defined, it’s as easy as pie:

float myAngle = 0f; //angle in degrees
Vector3 myAxis = Vector3.up; //whatever axis you want
Quaternion rot = Quaternion.AngleAxis(myAngle, myAxis);
myObject.transform.rotation = rot;

You may need to try it a few times to get a feel for it.