正方体效果图
代码
osgViewer::Viewer viewer;
//创建一个正方体
osg::ref_ptr<osg::Box> box = new osg::Box;
box->setCenter(osg::Vec3(0.0, 0.0, 0.0));
box->setHalfLengths(osg::Vec3(30.0, 30.0, 30.0));
osg::ref_ptr<osg::ShapeDrawable> sd2 = new osg::ShapeDrawable(box.get());
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(sd2.get());
osg::Group* root = new osg::Group;
root->addChild(geode);
//添加贴图
root->getOrCreateStateSet()->setTextureAttribute(0, new osg::Texture2D(osgDB::readImageFile("E:\\vs2022\\obj\\wabi_yellow.jpg")));
root->getOrCreateStateSet()->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
viewer.setSceneData(root);
viewer.realize();
viewer.run();
其他形状
osg::ref_ptr<osg::Geode> createCylinder() {
osg::ref_ptr<osg::TessellationHints> hits = new osg::TessellationHints;
//值越小精度也就越小
hits->setDetailRatio(0.8f);
//创建一个圆柱
osg::ref_ptr<osg::Cylinder> cy = new osg::Cylinder;
//直接用几何对象初始化实例
osg::ref_ptr<osg::ShapeDrawable> sd = new osg::ShapeDrawable(cy);
cy->setCenter(osg::Vec3(50.0, 0.0, 0.0));
cy->setHeight(30);
cy->setRadius(30);
sd->setTessellationHints(hits);
//创建一个长方体
osg::ref_ptr<osg::Box> box = new osg::Box;
box->setCenter(osg::Vec3(-50.0, 0.0, 0.0));
box->setHalfLengths(osg::Vec3(30.0, 30.0, 30.0));
osg::ref_ptr<osg::ShapeDrawable> sd2 = new osg::ShapeDrawable(box.get());
//创建一个圆球
osg::ref_ptr<osg::Sphere> sphere = new osg::Sphere;
sphere->set(osg::Vec3(0.0, 0.0, 50.0), 30);
osg::ref_ptr<osg::ShapeDrawable> sd3 = new osg::ShapeDrawable(sphere.get());
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(sd.get());
geode->addDrawable(sd2.get());
geode->addDrawable(sd3.get());
return geode;
}