開発環境 Microsoft Visual C# 2010 Express (SP1)
実行環境 Microsoft Windows XP Home Edition (SP3)
プロジェクトの種類 空のプロジェクト
プロジェクト名 Quaternion

Program.cs
// Quaternion5 回転とSlerp
using System;
using Microsoft.Xna.Framework; // .NET参照
 
class Program
{
    static void Main()
    {
        float rad = MathHelper.ToRadians(30);
        float y = (float)Math.Sin(rad);
        float r = (float)Math.Cos(rad);
        Vector3 v1 = new Vector3(r, y, 0);
        Vector3 v2 = new Vector3(0, y, r);
        Print(v1);
        Print(v2);
 
        // 外積で回転軸ベクトルを求める
        Vector3 cross = Vector3.Cross(v2, v1);
        cross.Normalize();
        Print(cross);
 
        // 内積でベクトル間の角度を求める
        float dot = Vector3.Dot(v1, v2); // |v1||v2|cosθ
        float angle = (float)Math.Acos(dot);
        Console.WriteLine(string.Format("angle={0:f2}", MathHelper.ToDegrees(angle)));
 
        Console.WriteLine("回転");
        Quaternion p = new Quaternion(v1, 0);
        for (int t = 0; t <= 4; t++)
        {
            Quaternion rot = Quaternion.CreateFromAxisAngle(cross, angle * t / 4);
            Quaternion q = Quaternion.Conjugate(rot) * p * rot;
            Console.Write(string.Format("t={0} / ", t));
            Print(q);
        }
 
        Console.WriteLine("Quaternion.Slerp");
        Quaternion q1 = new Quaternion(v1, 0);
        Quaternion q2 = new Quaternion(v2, 0);
        for (int t = 0; t <= 4; t++)
        {
            Quaternion q = Quaternion.Slerp(q1, q2, t / (float)4);
            Console.Write(string.Format("t={0} / ", t));
            Print(q);
        }
 
        Console.ReadLine();
    }
 
    static void Print(Vector3 v)
    {
        Console.WriteLine(string.Format("x={0:f2} y={1:f2} z={2:f2} len={3:f2}",
            v.X, v.Y, v.Z, v.Length()));
    }
 
    static void Print(Quaternion q)
    {
        Console.WriteLine(string.Format("x={0:f2} y={1:f2} z={2:f2} w={3:f2} len={4:f2}",
            q.X, q.Y, q.Z, q.W, q.Length()));
    }
}
 

出力
x=0.87 y=0.50 z=0.00 len=1.00
x=0.00 y=0.50 z=0.87 len=1.00
x=-0.45 y=0.77 z=-0.45 len=1.00
angle=75.52
回転
t=0 / x=0.87 y=0.50 z=0.00 w=0.00 len=1.00
t=1 / x=0.75 y=0.60 z=0.29 w=0.00 len=1.00
t=2 / x=0.55 y=0.63 z=0.55 w=0.00 len=1.00
t=3 / x=0.29 y=0.60 z=0.75 w=0.00 len=1.00
t=4 / x=0.00 y=0.50 z=0.87 w=0.00 len=1.00
Quaternion.Slerp
t=0 / x=0.87 y=0.50 z=0.00 w=0.00 len=1.00
t=1 / x=0.75 y=0.60 z=0.29 w=0.00 len=1.00
t=2 / x=0.55 y=0.63 z=0.55 w=0.00 len=1.00
t=3 / x=0.29 y=0.60 z=0.75 w=0.00 len=1.00
t=4 / x=0.00 y=0.50 z=0.87 w=0.00 len=1.00
最終更新:2012年12月17日 14:25