1、要对模型的移动,缩放和旋转,要使用osg::Matrix对象中的translate()(移动),scale()(缩放),rotate()(旋转),那么要使用这些还必须有osg::MatrixTransform对象作为基础,此对象是对模型的位置进行管理的,可通过setMatrix()函数进行设置位置,以及通过addChild()添加模型,最后都加入到Group对象中,如以下代码是移动:
osg::ref_ptr<osg::MatrixTransform> trans=new osg::MatrixTransform();
trans->setMatrix(osg::Matrix::translate(0,0,2));//坐标轴是向左右是x轴(右正,左负),上下是z轴(上正,下负),向里向外是y轴(里正,外负)
trans->addChild(osgcool.get()); //从中心坐标向上移动2个单位
2、对模型同时缩放和移动,只需要相乘即可,如下一代码所示:
osg::ref_ptr<osg::MatrixTransform> scale=new osg::MatrixTransform();
scale->setMatrix(osg::Matrix::scale(0.5,0.5,0.5)*osg::Matrix::translate(0,0,-2));//向上移动2个单位,并且对其缩小整体0.5倍
scale->addChild(osgcool.get()); //移动和缩放相乘就是对模型的移动和缩放同时进行
3、对模型旋转45度可使用以下代码:
osg::ref_ptr<osg::MatrixTransform> rot=new osg::MatrixTransform();
rot->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(45.0),1,0,0)*osg::Matrix::scale(0.5,0.5,0.5)*osg::Matrix::translate(4,0,-2));
rot->addChild(osgcool.get()); //模型向下移动两个单位,向右移动四个单位,并且整体缩放0.5倍,且绕X轴转45度,
//其中osg::DegreesToRadians(45.0),1,0,0)是将度数转为弧度,对于rotate,中的1表示延x轴旋转,如果是-1则表示逆时旋转
4、然后将所有的MatrixTransform对象添加到Group中,如下代码所示:
root->addChild(osgcool.get());//在中间
root->addChild(trans.get());//在原点的上方
root->addChild(scale.get());//在原点的下方
root->addChild(rot.get());
最后的代码如下所示:
#include "stdafx.h"
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osg/Node>
#include <osg/MatrixTransform>
#include <osg/Matrix>
int _tmain(int argc, _TCHAR* argv[])
{
osgViewer::Viewer viewer;
osg::ref_ptr<osg::Group> root=new osg::Group();
osg::ref_ptr<osg::Switch> sw=new osg::Switch();
osg::ref_ptr<osg::Node> osgcool=osgDB::readNodeFile("osgcool.osgt");
osg::ref_ptr<osg::MatrixTransform> trans=new osg::MatrixTransform();
trans->setMatrix(osg::Matrix::translate(0,0,2));//坐标轴是向左右是x轴(右正,左负),上下是z轴(上正,下负),向里向外是y轴(里正,外负)
trans->addChild(osgcool.get()); //从中心坐标向上移动2个单位
osg::ref_ptr<osg::MatrixTransform> scale=new osg::MatrixTransform();
scale->setMatrix(osg::Matrix::scale(0.5,0.5,0.5)*osg::Matrix::translate(0,0,-2));//向上移动2个单位,并且对其缩小整体0.5倍
scale->addChild(osgcool.get()); //移动和缩放相乘就是对模型的移动和缩放同时进行
osg::ref_ptr<osg::MatrixTransform> rot=new osg::MatrixTransform();
rot->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(45.0),1,0,0)*osg::Matrix::scale(0.5,0.5,0.5)*osg::Matrix::translate(4,0,-2));
rot->addChild(osgcool.get()); //模型向下移动两个单位,向右移动四个单位,并且整体缩放0.5倍,且绕X轴转45度,
//其中osg::DegreesToRadians(45.0),1,0,0)是将度数转为弧度,对于rotate,中的1表示延x轴旋转,如果是-1则表示逆时旋转
root->addChild(osgcool.get());//在中间
root->addChild(trans.get());//在原点的上方
root->addChild(scale.get());//在原点的下方
root->addChild(rot.get());
viewer.setSceneData(root.get());
viewer.realize();
return viewer.run();
}
运行效果如下: