参考链接:
从零实现3D图像引擎:(12)构建支持欧拉和UVN的相机系统
LearnOpenGL CN——摄像机
头文件
#ifndef GLCAMERA_H
#define GLCAMERA_H
#include <QVector2D>
#include <QVector3D>
#include <QMatrix4x4>
#include <QObject>
class GLCamera
{
public:
GLCamera(float aspectRatio);
~GLCamera();
QMatrix4x4 getCameraMatrix();
void adjustFocus(const float &val);
void translate(const float &xOffset,const float &yOffset);
void rotate(const float &xOffset, const float &yOffset);
void resetCamera();
protected:
void initialize();
void updateProjection();
void updateFront();
private:
float m_fAspectRatio = 1.0f;
float m_fVerticalAngle = 45.0f;
float m_fNearPlane = 0.1f;
float m_fFarPlane = 100.0f;
float m_fYaw = -90.0f;
float m_fPitch = 0.0f;
QMatrix4x4 m_mat4Projection;
QVector3D m_position = QVector3D(0.0f,0.0f,10.0f);
QVector3D m_front = QVector3D(0.0f,0.0f,-10.0f);
QVector3D m_up = QVector3D(0.0f,1.0f,0.0f);
QVector3D m_realTimePostion = m_position;
QVector3D m_realTimeFront = m_front;
};
#endif // GLCAMERA_H
源文件
#include "glcamera.h"
#include <QtMath>
#include <QDebug>
GLCamera::GLCamera(float aspectRatio)
{
m_fAspectRatio = aspectRatio;
initialize();
}
GLCamera::~GLCamera()
{
}
QMatrix4x4 GLCamera::getCameraMatrix()
{
QMatrix4x4 view;
view.lookAt(m_realTimePostion,m_realTimePostion + m_realTimeFront,m_up);
return m_mat4Projection * view;
}
void GLCamera::adjustFocus(const float &val)
{
m_realTimePostion += m_realTimeFront * (val - 1);
}
void GLCamera::translate(const float &xOffset,
const float &yOffset)
{
m_realTimePostion += QVector3D(xOffset,-yOffset,0);
}
void GLCamera::rotate(const float &xOffset,const float &yOffset)
{
m_fYaw += xOffset;
m_fPitch -= yOffset;
if (m_fPitch > 89.0f)
m_fPitch = 89.0f;
if (m_fPitch < -89.0f)
m_fPitch = -89.0f;
updateFront();
}
void GLCamera::resetCamera()
{
m_realTimePostion = m_position;
m_realTimeFront = m_front;
}
void GLCamera::initialize()
{
updateProjection();
updateFront();
}
void GLCamera::updateProjection()
{
m_mat4Projection = QMatrix4x4();
m_mat4Projection.perspective(m_fVerticalAngle,m_fAspectRatio,m_fNearPlane,m_fFarPlane);
}
void GLCamera::updateFront()
{
QVector3D front;
front.setX(qCos(qDegreesToRadians(m_fYaw)) * qCos(qDegreesToRadians(m_fPitch)));
front.setY(qSin(qDegreesToRadians(m_fPitch)));
front.setZ(qSin(qDegreesToRadians(m_fYaw)) * qCos(qDegreesToRadians(m_fPitch)));
m_realTimeFront = front.normalized();
}