gpt4 book ai didi

c++ - 3d 相机有意外滚动

转载 作者:行者123 更新时间:2023-11-30 05:17:07 26 4
gpt4 key购买 nike

我一直在使用 C++ 在 opengl 中开发 3d 相机。

当我拿着相机环顾四周时,有时相机会出现意想不到的滚动,尤其是当我将相机旋转一圈时。

我怀疑这是一个浮点错误,但我不知道如何检测它。

这是相机类:

#ifndef CAMERA_H
#define CAMERA_H

#include <GL/glew.h>

#include <GLFW/glfw3.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/string_cast.hpp>

#include <iostream>

using glm::vec3;
using glm::mat4;
using glm::quat;

enum CamDirection {
CAM_FORWARD,
CAM_BACKWARD,
CAM_LEFT,
CAM_RIGHT
};


class Camera {
public:
void cameraUpdate();

mat4 getViewMatrix();

Camera();

Camera(vec3 startPosition);

void move(CamDirection dir, GLfloat deltaTime);

void look(double xOffset, double yOffset);

void update();

private:
mat4 viewMatrix;

const GLfloat camSpeed = 5.05f;

};

mat4 Camera::getViewMatrix() {
return viewMatrix;
}

Camera::Camera(){}


Camera::Camera(vec3 startPos):
viewMatrix(glm::lookAt(startPos, vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f)))
{}

void Camera::move(CamDirection dir, GLfloat deltaTime) {
mat4 trans;
const vec3 camForward = vec3(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2]);
const vec3 camRight = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);

if (dir == CAM_FORWARD)
trans = glm::translate(trans, (camSpeed * deltaTime) * camForward);
else if (dir == CAM_BACKWARD)
trans = glm::translate(trans, -1 * (camSpeed * deltaTime) * camForward);
else if (dir == CAM_RIGHT)
trans = glm::translate(trans, -1 * (camSpeed * deltaTime) * camRight);
else
trans = glm::translate(trans, (camSpeed * deltaTime) * camRight);

viewMatrix *= trans;
}

void Camera::look(double xOffset, double yOffset) {
// 2 * acos(q[3])
quat rotation = glm::angleAxis((GLfloat)xOffset, vec3( 0.0f, 1.0f, 0.0f));

viewMatrix = glm::mat4_cast(rotation) * viewMatrix;

rotation = glm::angleAxis((GLfloat)yOffset, vec3(-1.0f, 0.0f, 0.0f));

mat4 rotMatrix = glm::mat4_cast(rotation);

viewMatrix = rotMatrix * viewMatrix;
}

void Camera::update() {
}
#endif // CAMERA_H

最佳答案

我设法弄清楚了。尽管我必须完全重写它才能做到这一点。

我的问题出在这几行:

quat rotation = glm::angleAxis((GLfloat)xOffset, vec3( 0.0f, 1.0f, 0.0f));

viewMatrix = glm::mat4_cast(rotation) * viewMatrix;

rotation = glm::angleAxis((GLfloat)yOffset, vec3(-1.0f, 0.0f, 0.0f));

mat4 rotMatrix = glm::mat4_cast(rotation);

构建一个中间四元数来存储方向反而有效,我可以用这个替换 look 方法:

quat pitch = quat(vec3(-yOffset, 0.0f, 0.0f));
quat yaw = quat(vec3(0.f, xOffset, 0.f));

orientation = pitch * orientation * yaw;

通过在最后一行乘以方向,不会发生意外滚动。

关于c++ - 3d 相机有意外滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com