简体   繁体   English

相机跟随玩家opengl

[英]Camera following player opengl

I have been looking into this problem for a while now but I can't find a solution. 我已经研究这个问题已有一段时间了,但找不到解决方案。 Right now my camera follows the players position correctly but the rotation of the camera goes wrong. 现在,我的相机正确地跟随了玩家的位置,但是相机的旋转发生了错误。 If I only use one rotation it goes correctly, say of I rotate only along the x axis then it works fine. 如果我只旋转一圈,则可以正常进行,例如我仅沿x轴旋转,那么效果很好。 But the second I add another rotation say the 'y' things go wrong and the camera starts looking into the wrong direction. 但是第二次我又增加了一个旋转,说“ y”出了问题,相机开始朝错误的方向看。

Right now my camera only has a position and a rotation. 现在,我的相机只有一个位置和旋转角度。

Here is some code. 这是一些代码。

glm::vec4 cameraPosition;

//This gives the camera the distance it keaps from the player.
cameraPosition.x = 0.0;
cameraPosition.y = 0.0;
cameraPosition.z = 20.0;
cameraPosition.w = 0.0;

// mStartingModel is the rotation matrix of the player.
glm::vec4 result = mStartingModel * cameraPosition;

//here I set the camera's position and rotation. The z rotation is given a extra 180 degrees so the camera is behind the player.
CameraHandler::getSingleton().getDefaultCamera()->setPosition(Vector3f(-player->mPosition.x + result.x, -player->mPosition.y + result.y, -player->mPosition.z + result.z), Vector3f(-(player->mRotation.x + 180), -player->mRotation.y, -player->mRotation.z) );

Also know I am using opengl, c++ and glm. 也知道我正在使用opengl,c ++和glm。

If you want a simple behavior, using gluLookAt is probably the simplest option! 如果您想要一个简单的行为,使用gluLookAt可能是最简单的选择! More infos here . 更多信息在这里

Seeing that you use glm , consider something like 看到您使用glm ,请考虑类似

glm::mat4 CameraMatrix = glm::LookAt(
    cameraPosition, // the position of your camera, in world space
    cameraTarget,   // where you want to look at, in world space
    upVector        // probably glm::vec3(0,1,0), but (0,-1,0) would make you looking upside-down, which can be great too
);

As taken from this site on opengl tutorials . 如从本网站上的opengl教程所取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM