如何让相机跟随opengl中的3D物体?
我第一次使用opengl制作赛车,我面临的第一个问题是如何让相机以恒定的距离跟随汽车。这是键盘功能的代码。V是汽车的速度。
void OnSpecial(int key, int x, int y)
{
float step = 5;
switch(key) {
case GLUT_KEY_LEFTa:
carAngle = step;
V.z = carAngle ;
camera.Strafe(-step/2);
break;
case GLUT_KEY_RIGHT:
carAngle = -step;
V.z = carAngle ;
camera.Strafe(step/2);
break;
case GLUT_KEY_UP:
V.x += (-step);
camera.Walk(step/2);
break;
case GLUT_KEY_DOWN:
if(V.x<0)
{
V.x += step;
camera.Walk(-step/2);
}
break;
}
}
i'm making a car race for the first time using opengl,the first problem i face is how to make the camera follow the car with constant distance..here is the code for keyboard function.V is the velocity of the car.
void OnSpecial(int key, int x, int y)
{
float step = 5;
switch(key) {
case GLUT_KEY_LEFTa:
carAngle = step;
V.z = carAngle ;
camera.Strafe(-step/2);
break;
case GLUT_KEY_RIGHT:
carAngle = -step;
V.z = carAngle ;
camera.Strafe(step/2);
break;
case GLUT_KEY_UP:
V.x += (-step);
camera.Walk(step/2);
break;
case GLUT_KEY_DOWN:
if(V.x<0)
{
V.x += step;
camera.Walk(-step/2);
}
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许是这样的?
如果您不使用旧的且已弃用的 openGL API(glBegin 等),您将不得不执行类似的操作
Something like that maybe ?
It you're not using the old and deprecated openGL API (glBegin & stuff) you'll have to do something like
答案很简单。您拥有玩家控制的对象(汽车),因此您可以通过世界空间中的 ModelViewMatrix 获得其位置和方向(通常指向 3D 模型的中心)
要将其转换为正确的
ModelViewMatrix
,您必须:获取或构造汽车
ModelMatrix
作为double M[16]
< /strong>将其平移/旋转到新位置(驾驶舱内或在车后面)
所以 Z 轴指向您想要看到的方向。通常跟随距离是速度的函数
反转
M
,因此M=Inverse(M)
使用
M
作为ModelViewMatrix
渲染
简而言之:
有关您需要的其他内容,请查看我的答案:
The answer to that is simple. You have player controlled object (car) so you have its position and orientation via
ModelViewMatrix
in world space (usually pointed to the center of 3D model)To transform it to the correct follow
ModelViewMatrix
you must:obtain or construct car
ModelMatrix
asdouble M[16]
translate/rotate it to the new position (inside cockpit or behind car)
so the Z axis is pointing the way you want to see. Its usual to have the follow distance as a function of speed
Invert
M
soM=Inverse(M)
use
M
asModelViewMatrix
render
so in an nutshell:
for additional stuff you need for this look at my answer here: