简体   繁体   中英

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. But the second I add another rotation say the 'y' things go wrong and the camera starts looking into the wrong direction.

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.

If you want a simple behavior, using gluLookAt is probably the simplest option! More infos here .

Seeing that you use glm , consider something like

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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