编写一个类来做控制器:分别实现WSAD上下左右功能:
#pragma once
#include "../Common.h"
class TravelManipulator :public osgGA::CameraManipulator {
public:
TravelManipulator();
~TravelManipulator();
public:
//设置当前视口
virtual void setByMatrix(const osg::Matrixd&matrix);
//设置当前视口
virtual void setByInverseMatrix(const osg::Matrixd&matrix);
//得到当前矩阵
virtual osg::Matrixd getMatrix() const;
//得到当前矩阵
virtual osg::Matrixd getInverseMatrix() const;
virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us);
private:
//视点
osg::Vec3 mPosition;
//朝向
osg::Vec3 mRotation;
//移动步长
int mStep;
//旋转步长
float mRotateStep;
};
#include "TravelManipulator.h"
TravelManipulator::TravelManipulator() {
mPosition = osg::Vec3(0, 0, 50);
mRotation = osg::Vec3(0, 0, 0);
mStep = 0;
mRotateStep = 0.0;
}
TravelManipulator::~TravelManipulator() {
}
void TravelManipulator::setByMatrix(const osg::Matrixd&matrix) {
}
void TravelManipulator::setByInverseMatrix(const osg::Matrixd&matrix) {
}
osg::Matrixd TravelManipulator::getMatrix() const {
osg::Matrixd mat;
mat.makeTranslate(mPosition);
return mat * osg::Matrixd::rotate(mRotation[0], osg::X_AXIS, mRotation[1], osg::Y_AXIS, mRotation[2], osg::Z_AXIS);
}
osg::Matrixd TravelManipulator::getInverseMatrix() const {
osg::Matrixd mat;
mat.makeTranslate(mPosition);
return osg::Matrixd::inverse(mat * osg::Matrixd::rotate(mRotation[0], osg::X_AXIS, mRotation[1], osg::Y_AXIS, mRotation[2], osg::Z_AXIS));
}
bool TravelManipulator::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us) {
switch (ea.getEventType()) {
case osgGA::GUIEventAdapter::KEYDOWN:
if (ea.getKey()=='w'){
mPosition[2] += 2;
} else if (ea.getKey() == 's') {
mPosition[2] -= 2;
} else if (ea.getKey() == 'a') {
mPosition[0] -= 2;
} else if (ea.getKey() == 'd') {
mPosition[0] += 2;
}
break;
default:
break;
}
return false;
}
调用:
int main(int argc, char** argv) {
for (int i = 0; i < argc; i++) {
printf(argv[i]);
printf("\n");
}
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();
viewer->addEventHandler(new osgViewer::WindowSizeHandler);
viewer->addEventHandler(new osgViewer::StatsHandler);
osg::ref_ptr<osg::Group> root = new osg::Group;
root->addChild(osgDB::readNodeFile("xyz.osgt"));
viewer->setSceneData(root);
viewer->setCameraManipulator(new TravelManipulator());//关键
viewer->realize();
viewer->run();
return 0;
}