最近在搞QT上的OPENGL,有好多库都要自己写啊
哐哧哐哧写了一大顿,已经写好了,回过头来记录一下
这篇讲的时关于opengl自由摄像机的问题
写摄像机的思路是,写一个万能的摄像机基类,可以支持各种基本操作(没有添加左右晃镜头的功能)
然后如果你需要用到什么样的摄像机,继承基类,然后重写他的移动函数和改变镜头方向函数(这两个函数为虚函数)
这样的话,你不用考虑是什么类型的摄像机,把摄像机基类指针传过去然后就可以自动调用你自己写的函数
!!!!!
注意此类用的是右手坐标系
!!!!!
代码如下:
基类摄像机
// camera.h
#pragma once
#ifndef CAMERA_H
#define CAMERA_H
#include<QObject>
#include<QVector3D>
#include<QVector4D>
#include<QMatrix4x4>
#include<QtMath>
namespace LB
{
/*
this is the coordinate be using
^ z
|
|
|
/----------> y
/
/
V x
*/
class Camera:public QObject
{
Q_OBJECT
public:
// pre_declare
enum Direction{
None=0,
Up=1,
Down=2,
Left=3,
Right=4,
Front=5,
Rear=6
};
Q_ENUMS(Direction)
// function
Camera();
virtual ~Camera(){}
void setCameraPosition(QVector3D p);
void setSpeedMove(float s);
void setSpeedWaggle(float s);
void setDirectionUp(QVector3D d);
void setDirectionLook(QVector3D d);
void setVerticalAngle(float a);
void setAspectRatio(float a);
void setNearPlane(float n);
void setFarPlane(float f);
// operate function
virtual void move(Direction d);
virtual void waggle(Direction d);
virtual void printInfo(); // Debug Method
// get status function
QVector4D getCameraPosition() const;
QVector4D getDirectionLook() const;
QVector4D getDirectionUp() const;
float getSpeedMove() const;
float getSpeedWaggle() const;
float getVerticalAngle() const;
float getAspetRatio() const;
float getNearPlane() const;
float getFarPlane() const;
// get matrix
QMatrix4x4 getViewMatrix();
QMatrix4x4 getViewMatrixLeftHand();
QMatrix4x4 getProjectionMatrix();
protected:
QVector4D position;
// the position of the free_camera
QVector4D direction_look;
//the look_direction
QVector4D direction_up;
float speed_move;
// the speed of camera moving
float speed_waggle;
// the speed of camera wagglling
float vertical_angle;
// angle of vertical field
float aspect_ratio;
// ration of width/height
float near_plane;
// the projection's near plane
float far_plane;
// the projection's far plane
};
}
#endif // CAMERA_H
// camera.cpp
#include "camera.h"
LB::Camera::Camera():
position(1.0f,0.0f,0.0f,1.0f),
direction_look(-1.0f,0.0f,0.0f,0.0f),
direction_up(0.0f,0.0f,1.0f,0.0f),
speed_move(0.02f),
speed_waggle(0.05f),
vertical_angle(90),
aspect_ratio(1.0f),
near_plane(