Skip to content

Instantly share code, notes, and snippets.

@fubar-coder
Created January 10, 2019 17:05
Show Gist options
  • Save fubar-coder/fa85cfc7b220c22c5d2dba8682a2fbd7 to your computer and use it in GitHub Desktop.
Save fubar-coder/fa85cfc7b220c22c5d2dba8682a2fbd7 to your computer and use it in GitHub Desktop.
Create Quaternion from two unit vectors for rotation
using System.Numerics;
static class Rotation
{
private static Quaternion CreateFromUnitVectors(Vector3 from, Vector3 to)
{
Vector3 v1;
var r = Vector3.Dot(from, to) + 1;
if (r < 0.000001f)
{
r = 0;
if (Math.Abs(from.X) > Math.Abs(to.X))
{
v1 = new Vector3(-from.Y, from.X, 0);
}
else
{
v1 = new Vector3(0, -from.Z, from.Z);
}
}
else
{
v1 = Vector3.Cross(from, to);
}
var q = new Quaternion(v1, r);
return Quaternion.Normalize(q);
}
}
@fubar-coder
Copy link
Author

fubar-coder commented Jan 10, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment