OSG 节点回调示例(旋转的球)
前言:最近开始进一步学习OSG,希望有所回报!
本文代码主要是通过节点回调,实现图元旋转!代码如下:
#include <osgViewer/Viewer> #include <osg/NodeCallback> #include <osg/Node> #include <osg/Group> #include <osg/Geode> #include <osg/ShapeDrawable> #include <osg/MatrixTransform> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> osg::ref_ptr<osg::Geode> createShape() { //创建一个叶节点 osg::ref_ptr<osg::Geode> geode = new osg::Geode(); //设置半径 float radius = 0.8f; //创建精细度对象,精细度越高,细分就越多 osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints(); hints->setDetailRatio(0.5f); //添加一个球体 geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f, 0.0f, 0.0f), radius), hints.get())); //添加一个正方体 geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(2.0f, 0.0f, 0.0f), 2*radius), hints.get())); return geode.get(); } class SphereCallback : public osg::NodeCallback { public: SphereCallback():angle(0), scale(1){} virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { //创建矩阵变换节点 osg::ref_ptr<osg::MatrixTransform> mt = dynamic_cast<osg::MatrixTransform*>(node); //创建矩阵 osg::Matrix mr; mr.makeRotate(angle, osg::Vec3(0.f, 0.f, 1.f)); //mr.makeScale(scale, scale, scale); mt->setMatrix(mr); angle += 0.1f; //scale -= 0.001f; //if (scale == 0.0f) //scale = 1.0f; traverse(node, nv); } private: double angle; double scale; }; int main() { osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer(); osg::ref_ptr<osg::Group> root = new osg::Group(); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); geode = createShape(); //创建矩阵变换节点 osg::ref_ptr<osg::MatrixTransform> mt = new osg::MatrixTransform(); mt->addChild(geode.get()); mt->setUpdateCallback(new SphereCallback()); root->addChild(mt.get()); //优化场景数据 osgUtil::Optimizer optimizer; optimizer.optimize(root.get()); viewer->setSceneData(root.get()); viewer->realize(); viewer->run(); return 0; }
运行截图: