📜  统一围绕点旋转矢量 - C# (1)

📅  最后修改于: 2023-12-03 15:11:41.077000             🧑  作者: Mango

统一围绕点旋转矢量 - C#

在计算机图形学中,有时需要对一个矢量在三维空间中进行旋转操作。而在旋转操作中,旋转轴常常是固定的,因此需要选择围绕旋转轴上哪个点进行旋转,这就是统一围绕点旋转矢量。下面将介绍在 C# 中实现这一操作的方法。

实现步骤
  1. 首先需要定义旋转轴和旋转角度。
Vector3 axis = new Vector3(0, 1, 0); // 旋转轴
float angle = 30; // 旋转角度,单位为度
  1. 然后需要选择围绕哪个点进行旋转,以及要旋转的矢量。
Vector3 point = new Vector3(1, 2, 3); // 围绕点
Vector3 vector = new Vector3(4, 5, 6); // 要旋转的矢量
  1. 将围绕点平移到原点上。
Vector3 translatedVector = vector - point;
  1. 计算旋转矩阵。
float radians = angle * (float)Math.PI / 180; // 角度转为弧度
float cos = (float)Math.Cos(radians);
float sin = (float)Math.Sin(radians);

Matrix4x4 rotationMatrix = new Matrix4x4();
rotationMatrix.m00 = cos + axis.x * axis.x * (1 - cos);
rotationMatrix.m01 = axis.x * axis.y * (1 - cos) - axis.z * sin;
rotationMatrix.m02 = axis.x * axis.z * (1 - cos) + axis.y * sin;
rotationMatrix.m03 = 0;
rotationMatrix.m10 = axis.y * axis.x * (1 - cos) + axis.z * sin;
rotationMatrix.m11 = cos + axis.y * axis.y * (1 - cos);
rotationMatrix.m12 = axis.y * axis.z * (1 - cos) - axis.x * sin;
rotationMatrix.m13 = 0;
rotationMatrix.m20 = axis.z * axis.x * (1 - cos) - axis.y * sin;
rotationMatrix.m21 = axis.z * axis.y * (1 - cos) + axis.x * sin;
rotationMatrix.m22 = cos + axis.z * axis.z * (1 - cos);
rotationMatrix.m23 = 0;
rotationMatrix.m30 = 0;
rotationMatrix.m31 = 0;
rotationMatrix.m32 = 0;
rotationMatrix.m33 = 1;
  1. 计算旋转后的矢量。
Vector3 rotatedVector = rotationMatrix * translatedVector;
  1. 将旋转后的矢量平移到原来的位置上。
Vector3 finalVector = rotatedVector + point;
  1. 完成。
完整代码片段
Vector3 axis = new Vector3(0, 1, 0); // 旋转轴
float angle = 30; // 旋转角度,单位为度
Vector3 point = new Vector3(1, 2, 3); // 围绕点
Vector3 vector = new Vector3(4, 5, 6); // 要旋转的矢量

Vector3 translatedVector = vector - point;

float radians = angle * (float)Math.PI / 180;
float cos = (float)Math.Cos(radians);
float sin = (float)Math.Sin(radians);

Matrix4x4 rotationMatrix = new Matrix4x4();
rotationMatrix.m00 = cos + axis.x * axis.x * (1 - cos);
rotationMatrix.m01 = axis.x * axis.y * (1 - cos) - axis.z * sin;
rotationMatrix.m02 = axis.x * axis.z * (1 - cos) + axis.y * sin;
rotationMatrix.m03 = 0;
rotationMatrix.m10 = axis.y * axis.x * (1 - cos) + axis.z * sin;
rotationMatrix.m11 = cos + axis.y * axis.y * (1 - cos);
rotationMatrix.m12 = axis.y * axis.z * (1 - cos) - axis.x * sin;
rotationMatrix.m13 = 0;
rotationMatrix.m20 = axis.z * axis.x * (1 - cos) - axis.y * sin;
rotationMatrix.m21 = axis.z * axis.y * (1 - cos) + axis.x * sin;
rotationMatrix.m22 = cos + axis.z * axis.z * (1 - cos);
rotationMatrix.m23 = 0;
rotationMatrix.m30 = 0;
rotationMatrix.m31 = 0;
rotationMatrix.m32 = 0;
rotationMatrix.m33 = 1;

Vector3 rotatedVector = rotationMatrix * translatedVector;

Vector3 finalVector = rotatedVector + point;