osg中使用MatrixTransform来实现模型的平移/旋转/缩放

来源:互联网 发布:plc显示屏编程 编辑:程序博客网 时间:2024/05/22 00:48

MatrixTransform是从Transform - Group继承而来,因此可以在它的下面挂接Node对象。

通过设置其矩阵,来实现其下子节点的模型变换。

-- 用局部坐标系来理解(局部坐标系又称惯性坐标系,其与模型的相对位置在变换的过程中始终不变)

如下代码:

 
01// 创建圆柱体
02double r = 0.5;
03double h = 3.0;
04osg::Vec3 orginPt(0.0, 0.0, 0.0);
05osg::ref_ptr<osg::Geode> cylinderGeode =new osg::Geode;
06osg::ref_ptr<osg::Cylinder> geoCylinder =new osg::Cylinder(orginPt, r, h);
07osg::ref_ptr<osg::ShapeDrawable> cylinderDrawable =new osg::ShapeDrawable(geoCylinder.get());
08cylinderDrawable->setColor(osg::Vec4(1.0f,0.0f,0.0f,1.0f));
09cylinderGeode->addDrawable(cylinderDrawable.get());
10  
11// -- 以下操作都是针对局部坐标系而言 --
12// 先将圆柱体平移(20.0, -12.0, -35.0)
13// 再将z轴方向旋转至向量n方向  此时局部坐标系的z轴和n向量一致
14// 接着,将旋转后的模型的沿z方向平移0.5*h长度 (全局坐标系,相当于沿n方向平移0.5*h长度)
15// 最后将模型放大2倍
16osg::Vec3 n(1.0, 1.0, -1.0);
17osg::Vec3 z(0.0, 0.0, 1.0);
18n.normalize();
19osg::ref_ptr<osg::MatrixTransform> mt =new osg::MatrixTransform;
20mt->setMatrix(osg::Matrix::scale(osg::Vec3(2.0, 2.0, 2.0))* 
21             osg::Matrix::translate(osg::Vec3(0, 0, 0.5*h))*
22        osg::Matrix::rotate(z, n)*
23        osg::Matrix::translate(osg::Vec3(20.0, -12.0, -35.0)));
24mt->addChild(cylinderGeode);

根据上面的特点,可以计算变化后的模型的三维坐标。

对于下图的包含关系(MatrixTransformA中包含一个MatrixTransformB,MatrixTransformB中包含一个模型

那么,模型的新坐标 (X, Y, Z) = (x,y,z)* B.matrix * A.matrix;

原创粉丝点击