爆炸模拟示例
爆炸模拟示例的代码如程序清单11-4 所示:
/* 爆炸模拟示例 */
void explosion_11_4()
{
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->x = 40;
traits->y = 40;
traits->width = 600;
traits->height = 480;
traits->windowDecoration = true;
traits->doubleBuffer = true;
traits->sharedContext = 0;
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
osg::ref_ptr<osg::Camera> camera = viewer->getCamera();
camera->setGraphicsContext(gc.get());
camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
camera->setDrawBuffer(buffer);
camera->setReadBuffer(buffer);
osg::ref_ptr<osg::Group> root = new osg::Group();
// 添加爆炸效果
root->addChild(createExplode());
// 优化场景数据
osgUtil::Optimizer optimize;
optimize.optimize(root.get());
viewer->setSceneData(root.get());
viewer->realize();
viewer->run();
}
// 创建爆炸效果
osg::ref_ptr<osg::Node> createExplode()
{
osg::ref_ptr<osg::Group> explode = new osg::Group();
// 风向
osg::Vec3 wind(1.0, 0.0, 0.0);
// 位置
osg::Vec3 position(0.0, 0.0, -10.0);
// 爆炸模拟,10.0为缩放比,默认为1.0,不缩放
osg::ref_ptr<osgParticle::ExplosionEffect> explosion = new osgParticle::ExplosionEffect(position,10.0);
// 碎片模拟
osg::ref_ptr<osgParticle::ExplosionDebrisEffect> explosionDebri = new osgParticle::ExplosionDebrisEffect(position, 10.0);
// 烟模拟
osg::ref_ptr<osgParticle::SmokeEffect> smoke = new osgParticle::SmokeEffect(position, 10.0);
// 火焰模拟
osg::ref_ptr<osgParticle::FireEffect> fire = new osgParticle::FireEffect(position, 10.0);
// 设置风向
explosion->setWind(wind);
explosionDebri->setWind(wind);
smoke->setWind(wind);
fire->setWind(wind);
// 添加子节点
explode->addChild(explosion.get());
explode->addChild(explosionDebri.get());
explode->addChild(smoke.get());
explode->addChild(fire.get());
return explode.get();
}
运行程序,截图如图11-6 所示
图11-6爆炸模拟示例图