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

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

转自:http://www.cnblogs.com/kekec/archive/2011/08/15/2139893.html#undefined

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

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

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

如下代码:

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

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

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

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

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