我已经尽我最大的努力创造了一个模仿第一人称相机风格的相机。我刚刚从旧的 OpenGL 渲染方法切换,现在准备处理相机矩阵。这是我的相机更新代码。
void Camera::update(float dt)
{
// Get the distance the camera has moved
float distance = dt * walkSpeed;
// Get the current mouse position
mousePos = mouse->getPosition();
// Translate the change to yaw and pitch
angleYaw -= ((float)mousePos.x-400.0f)*lookSpeed/40;
anglePitch -= ((float)mousePos.y-300.0f)*lookSpeed/40;
// Clamp the camera to a max/min viewing pitch
if(anglePitch > 90.0f)
anglePitch = 90.0f;
if(anglePitch < -90.0f)
anglePitch = -90.0f;
// Reset the mouse position
mouse->setPosition(mouseReset);
// Check for movement events
sf::Event event;
while (window->pollEvent(event))
{
// Calculate the x, y and z values of any movement
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::W)
{
position.x -= (float)sin(angleYaw*M_PI/180)*distance*25;
position.z += (float)cos(angleYaw*M_PI/180)*distance*25;
position.y += (float)sin(anglePitch * M_PI / 180) * distance * 25;
angleYaw = 10.0;
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::S)
{
position.x += (float)sin(angleYaw*M_PI/180)*distance*25;
position.z -= (float)cos(angleYaw*M_PI/180)*distance*25;
position.y -= (float)sin(anglePitch * M_PI / 180) * distance * 25;
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)
{
position.x += (float)cos(angleYaw*M_PI/180)*distance*25;
position.z += (float)sin(angleYaw*M_PI/180)*distance*25;
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::A)
{
position.x -= (float)cos(angleYaw*M_PI/180)*distance*25;
position.z -= (float)sin(angleYaw*M_PI/180)*distance*25;
}
}
// Update our camera matrix
camMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(-position.x, -position.z, -position.y));
camMatrix = glm::rotate(camMatrix, angleYaw, glm::vec3(0, 1, 0));
camMatrix = glm::rotate(camMatrix, anglePitch, glm::vec3(1, 0, 0));
}
最后 3 行是我假设用与翻译相反的方式更新相机的内容(y 和 z 切换为我正在使用的格式)。我做错了顺序吗?
这是我非常简单的着色器:
#version 120
attribute vec4 position;
uniform mat4 camera;
void main()
{
gl_Position = position * camera;
}
#version 120
void main(void)
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
这只是制作了一个红色三角形。相机围绕三角形旋转,这不是我想要的。我想让它旋转相机。我认为将相机矩阵乘以每个顶点会在相机空间中进行渲染。或者我还需要将它乘以投影矩阵吗?
移动 w、a、s 或 d 会同时放大非常近的位置,并且会扭曲整个视图,到处都是红色碎片。