OSG 学习第四课:绘制贴图正方体

正方体效果图

效果图

代码

    osgViewer::Viewer viewer;

    //创建一个正方体
    osg::ref_ptr 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 sd2 = new osg::ShapeDrawable(box.get());

    osg::ref_ptr 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 createCylinder() {
    osg::ref_ptr hits = new osg::TessellationHints;
    //值越小精度也就越小
    hits->setDetailRatio(0.8f);

    //创建一个圆柱
    osg::ref_ptr cy = new osg::Cylinder;
    //直接用几何对象初始化实例
    osg::ref_ptr 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 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 sd2 = new osg::ShapeDrawable(box.get());

    //创建一个圆球
    osg::ref_ptr sphere = new osg::Sphere;
    sphere->set(osg::Vec3(0.0, 0.0, 50.0), 30);
    osg::ref_ptr sd3 = new osg::ShapeDrawable(sphere.get());

    osg::ref_ptr geode = new osg::Geode;
    geode->addDrawable(sd.get());
    geode->addDrawable(sd2.get());
    geode->addDrawable(sd3.get());
    return geode;
}

你可能感兴趣的:(OSG 学习第四课:绘制贴图正方体)