示例功能:示例里面有两个模型,一个是牛,另一个是飞机。鼠标右键时牛和飞机都隐藏,鼠标左键双击时牛和飞机都显示,按键盘上面的LEFT键,显示牛,按键盘上面的RIGHT键显示飞机。其中显示与隐藏节点使用的是setNodeMask(bool)。bool的值为0的时候是隐藏,1的时候是显示。
#include<osgDBReadFile> #include<osgViewerViewer> #include<osgNode> class UseEventHandler :public osgGA::GUIEventHandler { public: virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa); if (!viewer)return false; switch (ea.getEventType()) { case osgGA::GUIEventAdapter::KEYDOWN: { if (ea.getKey() == 0xFF51) { viewer->getSceneData()->asGroup()->getChild(1)->setNodeMask(0); viewer->getSceneData()->asGroup()->getChild(0)->setNodeMask(1); } if (ea.getKey() == 0xFF53) { viewer->getSceneData()->asGroup()->getChild(0)->setNodeMask(0); viewer->getSceneData()->asGroup()->getChild(1)->setNodeMask(1); } break; } case osgGA::GUIEventAdapter::PUSH: if (ea.getButton() == 4) { viewer->getSceneData()->asGroup()->getChild(0)->setNodeMask(0); viewer->getSceneData()->asGroup()->getChild(1)->setNodeMask(0); } break; case osgGA::GUIEventAdapter::DOUBLECLICK: if (ea.getButton() == 1) { viewer->getSceneData()->asGroup()->getChild(0)->setNodeMask(1); viewer->getSceneData()->asGroup()->getChild(1)->setNodeMask(1); } break; default: break; } return false; } }; void main() { osgViewer::Viewer viewer; osg::ref_ptr<osg::Group> root = new osg::Group(); root->addChild(osgDB::readNodeFile("cow.osg")); root->addChild(osgDB::readNodeFile("glider.osg")); viewer.setSceneData(root.get()); viewer.addEventHandler(new UseEventHandler); viewer.realize(); viewer.run(); }
结果图: