Nic*_*ell 3 c++ opengl transform rotation matrix
我在OpenGL中实现了一个简单的相机系统.我在投影矩阵下设置了gluPerspective,然后在ModelView矩阵上使用gluLookAt.在此之后我有我的主渲染循环,它检查键盘事件,如果按下任何箭头键,修改角速度和前进速度(我只旋转y轴并移动z(向前)).然后我使用以下代码移动视图(deltaTime是自上一帧渲染以来的时间量,以秒为单位,以便从帧速率分离移动):
//place our camera
newTime = RunTime(); //get the time since app start
deltaTime = newTime - time; //get the time since the last frame was rendered
time = newTime;
glRotatef(view.angularSpeed*deltaTime,0,1,0); //rotate
glTranslatef(0,0,view.forwardSpeed*deltaTime); //move forwards
//draw our vertices
draw();
//swap buffers
Swap_Buffers();
Run Code Online (Sandbox Code Playgroud)
然后代码再次循环.我的绘制算法以a开头,以a glPushMatrix()
结束glPopMatrix()
.
每次调用glRotatef()和glTranslatef()都会在视图方向上向前推动视图向前移动速度.
然而,当我运行代码时,我的对象被绘制在正确的位置,但是当我移动时,运动是通过世界原点的方向(0,0,0 - 面向Z轴)完成的,而不是局部方向(我指向的地方)当我旋转时,旋转大约是(0,0,0),而不是相机的位置.
我最终得到了我的相机绕轨道(0,0,0)的奇怪效果,而不是现场旋转.
我根本没有glLoadIdentity()
在循环内的任何地方调用,我确信矩阵模式设置GL_MODELVIEW
为整个循环.
另一个奇怪的效果是,如果我glLoadIdentity()
在draw(
函数内部调用一个调用(在PushMatrix和PopMatrix调用之间,屏幕变黑,无论我在哪里看都找不到我绘制的对象.
有人知道我为了制作这个轨道(0,0,0)而不是当场旋转而搞砸了吗?
glRotate()
围绕World Origin旋转ModelView Matrix,因此要围绕某个任意点旋转,您需要转换矩阵以使该点位于原点,旋转然后转换回您开始的位置.
我想你需要的是这个
float x, y, z;//point you want to rotate around
glTranslatef(0,0,view.forwardSpeed*deltaTime); //move forwards
glTranslatef(x,y,z); //translate to origin
glRotatef(view.angularSpeed*deltaTime,0,1,0); //rotate
glTranslatef(-x,-y,-z); //translate back
//draw our vertices
draw();
//swap buffers
Swap_Buffers();
Run Code Online (Sandbox Code Playgroud)