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

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

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

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

如下代码:

 
01 // 创建圆柱体
02 double r = 0.5;
03 double h = 3.0;
04 osg::Vec3 orginPt(0.0, 0.0, 0.0);
05 osg::ref_ptr cylinderGeode = new osg::Geode;
06 osg::ref_ptr geoCylinder = new osg::Cylinder(orginPt, r, h);
07 osg::ref_ptr cylinderDrawable = new osg::ShapeDrawable(geoCylinder.get());
08 cylinderDrawable->setColor(osg::Vec4(1.0f,0.0f,0.0f,1.0f));
09 cylinderGeode->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倍
16 osg::Vec3 n(1.0, 1.0, -1.0);
17 osg::Vec3 z(0.0, 0.0, 1.0);
18 n.normalize();
19 osg::ref_ptr mt = new osg::MatrixTransform;
20 mt->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)));
24 mt->addChild(cylinderGeode);

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

对于下图的包含关系(MatrixTransform A中包含一个MatrixTransform B,MatrixTransform B中包含一个模型

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

你可能感兴趣的:(osg中使用MatrixTransform来实现模型的平移/旋转/缩放)