Hi. I need a function in my applicaiton that reproduces the same result as Vector3.RotateTowards. Does anyone knows the source code or have created a function like RotateTowards and want to share it?
I would appreciate it very much
Why can’t you use RotateTowards?
Are you needing an implementation of it independent of unity because your “application” is not being done in unity?
I ask, because someone might end up giving you an implementation that still relies on the unity API, and if you don’t have access to it, well it ain’t going to work.
With that said… from a mathematical perspective it’s pretty much get a vector orthogonal to both the input and target vectors (the cross product of the two), and then rotate the input vector by your angle around that orthogonal axis vector. Rotating a vector around an axis can be googled for very easily:
https://math.stackexchange.com/questions/511370/how-to-rotate-one-vector-about-another
Yes. My application is not done in Unity
Made this summurizing answer above and axis-angle-rotation here How to Rotate Around Axis? . But some methods are used from bullet physics. Methods are with same names as in unity, so you can write needed code disassembling unity or taking from github.
public static Vector3 RotateTowards(Vector3 current, Vector3 target, float maxRadiansDelta)
{
var angle = AngleBetweenVectors(current, target) * Mathf.Deg2Rad;
if (angle < maxRadiansDelta)
return target;
var rotationAxis = current.Cross(target);
var result = current;
RotateAround(ref result, Vector3.Zero, rotationAxis, maxRadiansDelta * Mathf.Rad2Deg);
return result;
}
// https://gist.github.com/kennir/1b545c55e2ab40d36ce536a1711d032d
// Example usage:
// Spin the object around the world origin at 20 degrees/second.
// RotateAround(transform.position, Vector3.zero, Vector3.up, 20 * Time.deltaTime);
private static void RotateAround(ref Vector3 objectPosition, Vector3 pos, Vector3 up, float degree)
{
Quaternion q = AngleAxis(degree, ref up);
objectPosition = Mul(q , objectPosition-pos) + pos;
}
// https://gist.github.com/HelloKitty/91b7af87aac6796c3da9
private static Quaternion AngleAxis(float degress, ref Vector3 axis)
{
if (axis.LengthSquared == 0.0f)
return Quaternion.Identity;
Quaternion result = Quaternion.Identity;
var radians = degress * Mathf.Deg2Rad;
radians *= 0.5f;
axis.Normalize();
axis = axis * (float)System.Math.Sin(radians);
result.X = axis.X;
result.Y = axis.Y;
result.Z = axis.Z;
result.W = (float)System.Math.Cos(radians);
return Quaternion.Normalize(result);
}