如何绕任意轴旋转点?
How to rotate a point around an arbitrary axis?
我想在OpenGL中围绕任意轴旋转一个点。我想利用它来旋转球体。
这是我到目前为止得到的:
float degreeBetweenTwoVec(glm::vec3 &a, glm::vec3 b)
{
float prod = b.x * a.x + b.y * a.y + b.z * a.z;
float mag_axis = sqrt((b.x * b.x) + (b.y * b.y) + (b.z * b.z));
float mag_vec = sqrt((a.x * a.x) + (a.y * a.y) + (a.z * a.z));
float degree = prod / (mag_axis * mag_vec);
return acos(degree) * 180.0 / PI;;
}
void rotAroundZ(glm::vec3 &point, float degree)
{
glm::vec3 n_point;
n_point.x = (point.x * cos(degree * PI / 180.0)) - (point.y * sin(degree * PI / 180.0));
n_point.y = (point.x * sin(degree * PI / 180.0)) + (point.y * cos(degree * PI / 180.0));
n_point.z = point.z;
point.x = n_point.x;
point.y = n_point.y;
point.z = n_point.z;
}
void rotAroundY(glm::vec3& point, float degree)
{
glm::vec3 n_point;
n_point.x = (point.x * cos(degree * PI / 180.0)) + (point.z * sin(degree * PI / 180.0));
n_point.y = point.y;
n_point.z = ((point.x * -1.0f) * sin(degree * PI / 180.0)) + (point.z * cos(degree * PI / 180.0));;
point.x = n_point.x;
point.y = n_point.y;
point.z = n_point.z;
}
void rotAroundA(glm::vec3& point, glm::vec3 &axis, float zdegree)
{
float xdegree = degreeBetweenTwoVec(axis, glm::vec3{ 1.0f, 0.0f, 0.0f });
float ydegree = degreeBetweenTwoVec(axis, glm::vec3{ 0.0f, 1.0f, 0.0f });
rotAroundZ(point, xdegree);
rotAroundY(point, ydegree);
rotAroundZ(point, zdegree);
rotAroundY(point, -ydegree);
rotAroundZ(point, -xdegree);
}
void rotAObject(Object& obj, glm::vec3 &axis, float degree)
{
axis = glm::normalize(axis);
translate(axis, glm::vec3{ axis.x, axis.y, axis.z });
for (int i = 0; i < obj.vertices.size(); i++)
{
rotAroundA(obj.vertices[i], axis, degree);
}
rotAroundA(obj.mp, axis, degree);
translate(axis, glm::vec3{ axis.x * -1.0f, axis.y * -1.0f, axis.z * -1.0f });
}
如果给定的轴恰好在全局轴之一上,则此方法可以正常工作。但是,如果不是,并且给定的轴基本上围绕其他东西旋转。有某种轴它正在旋转,但是一旦改变给定的轴,例如围绕z轴旋转它,它就会绕一个与以前完全不同的轴旋转。看起来对于给定轴可以采取的每个位置,对象实际上都在旋转其他一些轴。
任何帮助不胜感激!
我建议使用旋转矩阵。使用glm::rotate()
按轴和角度设置旋转矩阵。
将点转换为glm::vec4
并通过旋转矩阵进行转换:
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
glm::mat4 rot_mat = glm::rotate(glm::mat4(1.0f), glm::radians(degree), axis);
glm::vec3 n_point = glm::vec3(glm::vec4(point, 1.0f) * rot_mat);
相关文章:
- 与互斥锁相比,旋转锁可以保证上下文切换
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何绕任意轴旋转点?
- 矩阵乘法 - 如何使行星绕自己的轴旋转,并绕其母轴运行?
- 绕摄影机旋转opengl c++/设置旋转中心
- 使用四元数防止绕某个轴旋转
- 如何绕轴旋转点云
- 用四元数绕轴旋转矢量
- 绕Y轴旋转二维正方形,并使用DirectX或openGL以透视投影方式显示
- 绕轴旋转相机
- 使用单应性绕x/y轴旋转
- 点绕 z 轴旋转
- 如何旋转粒子系统,使其不绕世界轴旋转
- 为什么我的相机用这个数学绕一个点旋转
- 绕其中心旋转矩形
- Box2D c++绕点旋转
- 同时绕两个点旋转
- 函数使一个点绕另一个点旋转
- C++OpenGL绕轴直线旋转
- Directx11绕世界中心旋转