使用键旋转对象
Object rotation using keys
我想用键旋转立方体。这是代码的一部分。当我按左键时,立方体向左旋转,等等。我的目标是旋转立方体,所以我必须将其旋转x
并y
轴,这会导致问题。
我已经定义了mat4 rotation;
,并在按住键时使用它来分配旋转。当我按住钥匙时,它会旋转,例如向左旋转。然后我松开钥匙,物体回到初始位置(相机回到初始位置,因为物体没有移动)。我认为这个问题导致了在关键功能下面定义的auto rotateMat = rotation;
行。我做错了什么?
mat4 rotation; //global
if(keysPressed[GLFW_KEY_LEFT]){
timer -= delta;
rotation = rotate(mat4{}, timer * 0.5f, {0, 1, 0});
}
if(keysPressed[GLFW_KEY_RIGHT]){
timer += delta;
rotation = rotate(mat4{}, timer * 0.5f, {0, 1, 0});
}
if(keysPressed[GLFW_KEY_UP]){
timer += delta;
rotation = rotate(mat4{}, timer * 0.5f, {1, 0, 0});
}
if(keysPressed[GLFW_KEY_DOWN]){
timer -= delta;
rotation = rotate(mat4{}, timer * 0.5f, {1, 0, 0});
}
...
program.setUniform("ModelMatrix", rotation* cubeMat);
cube.render();
更新:
因此,当我使用矩阵变量作为全局变量而不是局部变量时,这个问题就解决了。
有多种
方法可以实现这种交互。一个更简单的方法是在每一帧而不是全局帧中创建相对平移,并将其添加到当前旋转中:
为此,必须将所有旋转的总和存储在全局变量中
//Global variable
mat4 total_rotate;
并计算每帧的相对平移:
//In the function
mat4 rotation;
if(keysPressed[GLFW_KEY_LEFT]){
rotation = rotate(mat4{}, delta, {0, 1, 0});
}
if(keysPressed[GLFW_KEY_RIGHT]){
rotation = rotate(mat4{}, -delta, {0, 1, 0});
}
if(keysPressed[GLFW_KEY_UP]){
rotation = rotate(mat4{}, delta, {1, 0, 0});
}
if(keysPressed[GLFW_KEY_DOWN]){
rotation = rotate(mat4{}, -delta, {1, 0, 0});
}
total_rotate = total_rotate * rotation;
...
program.setUniform("ModelMatrix", total_rotate * cubeMat);
cube.render();
作为替代方案,您可以存储两个旋转角度并计算每帧中的矩阵:
//Global variables
float rot_x = 0.0f, rot_y = 0.0f;
//In every frame
if(keysPressed[GLFW_KEY_LEFT]){
rot_x += delta;
}
if(keysPressed[GLFW_KEY_RIGHT]){
rot_x -= delta;
}
//Same for y
auto rotation = rotate(rotate(mat4{}, rot_y, {0, 1, 0}), rot_x, {1, 0, 0}
...
program.setUniform("ModelMatrix", rotation * cubeMat);
cube.render();
相关文章:
- 形状对象的旋转和缩放不正确C++
- 如何在OpenGL中正确旋转和缩放对象?
- 当表示为对象的一维向量时,有效地旋转 NxM 矩阵 (C++)
- 如何围绕对象旋转相机?
- 如何在 opengl 中仅旋转特定对象而不影响其他对象?
- 将四元数旋转的游戏对象旋转另一个四元数时出现问题
- 鼠标单击 OpenGL 时无法围绕其自己的中心旋转对象
- 无法在D2D1中旋转对象
- 如何使用OpenCV从图像中检测旋转对象
- OpenCV 检测多个旋转的缩放对象
- OpenGL c++ 中的旋转子对象
- 无法从非原点的其他位置旋转对象
- 在Qt5的OpenGL绘图中通过鼠标移动计算对象旋转角度
- 围绕另一个对象旋转对象
- 矩阵乘法 opengl 围绕对象旋转
- 对象旋转/平移后重新计算AABB正确
- 围绕另一个对象旋转的物体不断加速
- 在 C++/OpenGL 中围绕另一个对象旋转投影一个对象
- 如何在OpenGL中将对象旋转一定程度?有内置的命令吗?或者我必须使用公式吗
- 如何在其他部件旋转时阻止对象旋转