osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
viewer.setCameraManipulator( keyswitchManipulator.get() );
申请一个使用按键来切换操作器的类,即:osgGA::KeySwitchMatrixManipulator,意思是这样的,往这个类中添操作器,添的时候带个标识和快捷键,然后再把这个类添加到viewer当中,这样viewer运行的时候就可以通过按键来换操作器了,真方便。
源代码分析:osgGA\KeySwitchMatrixManipulator头文件
public:
typedef std::pair<std::string, osg::ref_ptr<CameraManipulator> > NamedManipulator;
typedef std::map<int, NamedManipulator> KeyManipMap;
virtual const char* className() const { return "KeySwitchMatrixManipulator"; }
/**
Add a camera manipulator with an associated name, and a key to
trigger the switch,
*/
void addMatrixManipulator(int key, std::string name, CameraManipulator *cm);
private:
KeyManipMap _manips;
osg::ref_ptr<CameraManipulator> _current;
用了一个map映射(C#中有Dictionary词典), map对象是模板类,需要关键字key和存储对象value两个模板参数,map中的key和value是一个pair结构中的两个分量:
源文件
bool KeySwitchMatrixManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& aa)
{
if (!_current) return false;
bool handled = false;
if (!ea.getHandled() && ea.getEventType()==GUIEventAdapter::KEYDOWN)
{
KeyManipMap::iterator it=_manips.find(ea.getKey());//找到按键如'E'
if(it != _manips.end())//不为空
{
CameraManipulator* selectedManipulator = it->second.second.get();//it为一个pair,key为pair.first value为pair.second
if (selectedManipulator!=_current)
{
OSG_INFO<<"Switching to manipulator: "<<it->second.first<<std::endl;
if ( !selectedManipulator->getNode() )
{
selectedManipulator->setNode(_current->getNode());
}
selectedManipulator->setByMatrix(_current->getMatrix());//设置当前矩阵
selectedManipulator->init(ea,aa);
_current = selectedManipulator;
}
handled = true;
}
}
return _current->handle(ea,aa) || handled;
}
添加数字切换
void KeySwitchMatrixManipulator::addNumberedMatrixManipulator(CameraManipulator *cm)
{
if(!cm) return;
addMatrixManipulator('1'+_manips.size(),cm->className(),cm);
}