简单操作
步骤:
- 先实例化一个
node,平移到x正轴的5
osg::ref_ptr<osg::Group> group = new osg::Group;
osg::ref_ptr<osg::MatrixTransform> max = new osg::MatrixTransform;
osg::ref_ptr<osg::Node> node = osgDB::readNodeFile("glider.osg");
max->addChild(node.get());
max->setMatrix(osg::Matrix::translate(5.0, 0.0, 0.0));
group->addChild(osgDB::readNodeFile("glider.osg"));
-
给
max一个旋转状态,让小飞机绕着Z轴在(0.0, 0.0, 0.0)点旋转,角速度为1。max->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0.0, 0.0, 0.0), osg::Z_AXIS, 1.0));理想状态下,应该是有一个小飞机在
(5.0, 0.0, 0.0)这个位置上原地旋转: -
结果 =》明显是失败了
-
分析一下原因
这里有一个知识点,
Callback的方法会覆盖掉前面的矩阵平移的操作。 -
有人要说了,那给旋转操作和矩阵操作换一下位置,后执行平移操作。结果当然是不行的,这里的
setXXX相当于设置的属性,而不是操作函数。影响是整个属性的对象。换言之,只有他们不是一个对象就不会覆盖掉了 -
重新创建一个
max2对象,给它一个平移操作;给max对象一个旋转操作;再将max2对象添加给max对象。osg::ref_ptr<osg::Node> node = osgDB::readNodeFile("glider.osg"); osg::ref_ptr<osg::MatrixTransform> max2 = new osg::MatrixTransform; max2->addChild(node.get()); max2->setMatrix(osg::Matrix::translate(5.0, 0.0, 0.0)); max->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(5.0, 0.0, 0.0), osg::Z_AXIS, 1.0)); max->addChild(max2.get()); -
看一下结果
-
完整代码
osg::ref_ptr<osg::MatrixTransform> max3 = new osg::MatrixTransform; osg::ref_ptr<osg::MatrixTransform> max4 = new osg::MatrixTransform; max4->addChild(node.get()); max4->setMatrix(osg::Matrix::translate(-5.0, 0.0, 0.0)); max3->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(-5.0, 0.0, 0.0), osg::Z_AXIS, 1.0)); max3->addChild(max4.get()); group->addChild(max3.get());
完整代码
#include <osgDB/ReadFile>
#include <osgGA/GUIEventAdapter>
#include <osgViewer/ViewerEventHandlers>
#include <osg/MatrixTransform>
#include <iostream>
using namespace std;
osg::ref_ptr<osg::Node> MatrixOperation() {
osg::ref_ptr<osg::Group> group = new osg::Group;
osg::ref_ptr<osg::MatrixTransform> max = new osg::MatrixTransform;
osg::ref_ptr<osg::Node> node = osgDB::readNodeFile("glider.osg");
osg::ref_ptr<osg::MatrixTransform> max2 = new osg::MatrixTransform;
osg::ref_ptr<osg::MatrixTransform> max3 = new osg::MatrixTransform;
osg::ref_ptr<osg::MatrixTransform> max4 = new osg::MatrixTransform;
max2->addChild(node.get());
max2->setMatrix(osg::Matrix::translate(5.0, 0.0, 0.0));
max->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(5.0, 0.0, 0.0), osg::Z_AXIS, 1.0));
max->addChild(max2.get());
max4->addChild(node.get());
max4->setMatrix(osg::Matrix::translate(-5.0, 0.0, 0.0));
max3->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(-5.0, 0.0, 0.0), osg::Z_AXIS, 1.0));
max3->addChild(max4.get());
group->addChild(node.get());
group->addChild(max.get());
group->addChild(max3.get());
return group;
}
int main() {
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
viewer->setSceneData(MatrixOperation().get());
viewer->run();
return 0;
}