第4课时《osg矩阵变换(上)》

8 篇文章 1 订阅


首先了解下几个概念:

 1.osg空间方向


          OSG坐标轴如上图图所示,x轴表示屏幕水平方向,y轴表示和屏幕垂直方向即屏幕里面方向,z轴表示屏幕垂直方向,每个箭头指向表示正方向 。而OpenGL的坐标轴有所不同,OpenGL的坐标轴(如上图所示):x正向:从左到右,中间为0, y正向:从下到上,中间为0, z正向:从里到外,显示器所在面为0

2. 模型矩阵变换

模型的移动、旋转、缩放其实都是对矩阵进行操作,矩阵可以当作一个特殊的结点加入到组结点中。

通过 osg::MatrixTransform 定义变换矩阵, 
   通过 setMatrix(osg::Matrix::translate(x, y, z)) 实现模型移动, 
   通过 setMatrix(osg::Matrix::scale(x, y, z)) 实现模型缩放, 
   通过 setMatrix(osg::Matrix::rotate(x, y, z)) 实现模型旋转。

可以通过下面的代码实现模型的移动、旋转、缩放:

#include <QApplication>
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osg/Node>
#include <osg/MatrixTransform>
#include <osgQt/GraphicsWindowQt>
#include <osgGA/TrackballManipulator>
#include <osgViewer/ViewerEventHandlers>
int main(int argc,char ** argv)
{
    QApplication app(argc,argv);
    osgQt::initQtWindowingSystem();
    osg::ref_ptr<osgViewer::Viewer> viewer= new osgViewer::Viewer;
    osg::ref_ptr<osg::Group> root = new osg::Group;
    osg::ref_ptr<osg::Node> osgcool = osgDB::readNodeFile("osgcool.osgt");
    //沿着z轴方向平移2个单位
    osg::ref_ptr<osg::MatrixTransform> trans = new osg::MatrixTransform;
    trans->setMatrix(osg::Matrix::translate(0, 0, 2));
    trans->addChild(osgcool.get());
    //模型缩放0.5倍,然后沿着z轴负方向平移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));
    scale->addChild(osgcool.get());
    //模型沿着x轴旋转45度,缩放0.5倍,然后沿着z轴负方向平移2个单位,x轴平移4个单位
    osg::ref_ptr<osg::MatrixTransform> rotate = new osg::MatrixTransform;
    rotate->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));
    rotate->addChild(osgcool.get());
    root->addChild(osgcool.get());
    root->addChild(trans.get());
    root->addChild(scale.get());
    root->addChild(rotate);
    viewer->setSceneData(root.get());
    viewer->setCameraManipulator(new osgGA::TrackballManipulator);
    viewer->addEventHandler(new osgViewer::StatsHandler);
    osgQt::setViewer(viewer.get());
    osgQt::GLWidget* glw= new osgQt::GLWidget;
    osgQt::GraphicsWindowQt *graphW= new osgQt::GraphicsWindowQt(glw);
    viewer->getCamera()->setViewport(new osg::Viewport(0,0,glw->width(),glw->height()));
    viewer->getCamera()->setGraphicsContext(graphW);
    glw->show();
    return app.exec();
}


  效果图如下: 


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值