今天需要实现一个osg半透明遮挡场景,在网上查了好多帖子,都不好用,不是遮挡不对,就是所有物体全透明了。最后终于在google找到一篇英文帖子,解决了问题。
具体实现半透明效果的代码如下:
- osg::MatrixTransform* createDoor3()
- {
- osg::ref_ptr<osg::ShapeDrawable> doorShape =
- new osg::ShapeDrawable( new osg::Box(osg::Vec3(0.0f, 0.0f, 0.0f), 2.0f, 2.0f, 2.0f) );
- doorShape->setColor( osg::Vec4(0.0f, 1.0f, 1.0f, 0.5f) ); // alpha value
- osg::StateSet* stateset = doorShape->getOrCreateStateSet();
- osg::ref_ptr<osg::BlendFunc> blendFunc = new osg::BlendFunc(); // blend func
- blendFunc->setSource(osg::BlendFunc::SRC_ALPHA);
- blendFunc->setDestination(osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
- stateset->setAttributeAndModes( blendFunc );
- stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
- osg::ref_ptr<osg::Geode> geode = new osg::Geode;
- geode->addDrawable( doorShape.get() );
- osg::ref_ptr<osg::MatrixTransform> trans = new osg::MatrixTransform;
- trans->addChild( geode.get() );
- return trans.release();
- }
然后把这个结点加载到场景中就可以了,效果如下图(场景中心红色立方体和边角的蓝色立方体就是上面的代码去掉半透明那部分代码):