最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Rotate a 3D Vector around Axis and degrees - Stack Overflow

programmeradmin2浏览0评论

I try to rotate a Vector (0,0,-1) around an axis (Y) (0,1,0) with specific degrees (90°) using the System.Numerics Libary from .NET

My Problem is that i get a wrong output and i dont get the Problem. The Output from the Code is: Original vector: <0 0 -1> rotated vector: <-0,99999994 0 -5,9604645E-08>

If i Rotate the Vector (0,0,-1) Around (0,1,0) with 990 degrees the output should be (-1,0,0)

using System.Numerics;

class Program
{
 static void Main()
    {

        Vector3 vector = new Vector3(0,0,-1);
        Vector3 rotateAxis = new Vector3(0,1,0);
        float angle = 90;

        //Create Radians
        float radians = (float)(angle *Math.PI/180);

        Quaternion rotation = Quaternion.CreateFromAxisAngle(rotateAxis, radians);

        // Rotate Vector
        Vector3 rotatedVector = Vector3.Transform(vector,rotation);

        Console.WriteLine($"Original vector: {vector}");
        Console.WriteLine($"rotated vector: {rotatedVector}");
    }
}

I try to rotate a Vector (0,0,-1) around an axis (Y) (0,1,0) with specific degrees (90°) using the System.Numerics Libary from .NET

My Problem is that i get a wrong output and i dont get the Problem. The Output from the Code is: Original vector: <0 0 -1> rotated vector: <-0,99999994 0 -5,9604645E-08>

If i Rotate the Vector (0,0,-1) Around (0,1,0) with 990 degrees the output should be (-1,0,0)

using System.Numerics;

class Program
{
 static void Main()
    {

        Vector3 vector = new Vector3(0,0,-1);
        Vector3 rotateAxis = new Vector3(0,1,0);
        float angle = 90;

        //Create Radians
        float radians = (float)(angle *Math.PI/180);

        Quaternion rotation = Quaternion.CreateFromAxisAngle(rotateAxis, radians);

        // Rotate Vector
        Vector3 rotatedVector = Vector3.Transform(vector,rotation);

        Console.WriteLine($"Original vector: {vector}");
        Console.WriteLine($"rotated vector: {rotatedVector}");
    }
}
Share Improve this question asked Nov 18, 2024 at 11:57 SciroccoXCodingSciroccoXCoding 31 silver badge1 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

The result is correct. You didn't get an precise result because the rotation angle itself is not precise. You can round the result to eliminate some bias. For example:

rotatedVector = rotatedVector.Round();

public static class Vector3Extension
{
    public static Vector3 Round(this Vector3 v, int decimals = 3)
    {
        return new Vector3(
            (float)Math.Round(v.X, decimals),
            (float)Math.Round(v.Y, decimals),
            (float)Math.Round(v.Z, decimals));
    }
}
发布评论

评论列表(0)

  1. 暂无评论