osg中控制节点显隐的节点Switch。利用上一篇文章中的回调过程,实现节点的动态显示与隐藏。
先看效果:
定义回调对象:
#pragma once
#include "osgInc.h"
class SwitchCallBack :public osg::NodeCallback {
public:
SwitchCallBack();
~SwitchCallBack();
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)override;
};
#include "SwitchCallBack.h"
SwitchCallBack::SwitchCallBack() {
}
SwitchCallBack::~SwitchCallBack() {
}
void SwitchCallBack::operator()(osg::Node* node, osg::NodeVisitor* nv) {
osg::ref_ptr<osg::Switch> sw = dynamic_cast<osg::Switch*>(node);
if (sw != nullptr && nv != nullptr) {
const osg::FrameStamp* fs = nv->getFrameStamp();
if (fs->getFrameNumber() % 50 == 0) {//获取当前场景运行的帧数
if (sw->getValue(0)){
sw->setValue(0, false);
} else {
sw->setValue(0, true);
}
if (sw->getValue(1)) {
sw->setValue(1, false);
} else {
sw->setValue(1, true);
}
}
}
traverse(node, nv);
}
运行示例:
void createSwitch() {
osg::ref_ptr<osg::Group> root = new osg::Group;
osg::ref_ptr<osg::Switch> sw = new osg::Switch;
root->addChild(sw);
osg::ref_ptr<osg::Node> cowNode = osgDB::readNodeFile("cow.osg");
osg::ref_ptr<osg::Node> ceepNode = osgDB::readNodeFile("cessna.osg");
osg::ref_ptr<osg::Node> clockNode = osgDB::readNodeFile("clock.osgt");
sw->addChild(cowNode);
sw->addChild(ceepNode);
root->addChild(clockNode);
sw->addUpdateCallback(new SwitchCallBack());
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();
viewer->addEventHandler(new osgViewer::WindowSizeHandler());
viewer->setSceneData(root.get());
viewer->realize();
viewer->run();
}
aaa