自定義回撥控制OSG模型進行移動操作
阿新 • • 發佈:2018-11-10
1、新建vs控制檯專案,勾選空專案
2、新建.h檔案命名為osg.h,用來包含用到的OSG標頭檔案
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osg/Node>
#include <osg/MatrixTransform>
#include <osgUtil/Optimizer>
3、新建cpp檔案,用來寫回調,以及主函式
4、在cpp檔案中加入以下程式碼。
//******************************************************************// // 此檔案中新增mycallback回撥函式和主程式 // //******************************************************************// #include "osg.h" #include <Windows.h> //添加回調 class mycallback:public osg::NodeCallback { public: mycallback(float pos) { m_pos=pos; } virtual void operator() (osg::Node* node,osg::NodeVisitor* nv) { osg::ref_ptr<osg::MatrixTransform> transpos=dynamic_cast<osg::MatrixTransform*>(node); if (nv&&transpos&&nv->getFrameStamp()) { //double time=nv->getFrameStamp()->getReferenceTime();獲取當前執行時間 m_pos++; //飛機執行下一個位置,可以在此設定translate三個引數數學值,讓它實現在固定路勁上飛行 transpos->setMatrix(osg::Matrix::translate(0.0f+cosf(0.02*m_pos),1.0f,0.0f+sinf(0.02*m_pos))* osg::Matrix::rotate(60,1.0f,0.0f,0.0f)); //Sleep(1000); } traverse(node,nv); } protected: int m_pos; }; int main() { //主函式 //建立viewer osgViewer::Viewer FirViewer; //建立group組節點 osg::ref_ptr<osg::Group>FirRoot=new osg::Group(); //載入模型NODE osg::ref_ptr<osg::Node>firnode1=osgDB::readNodeFile("D:\\OSG\\data\\glider.osg"); //建立模型矩陣變換matrix節點 osg::ref_ptr<osg::MatrixTransform> transpos=new osg::MatrixTransform(); //設定回撥 transpos->setUpdateCallback(new mycallback(1)); //為回撥傳入模型指標 transpos->addChild(firnode1); //將變換節點加入組節點 FirRoot->addChild(transpos); //載入viewer顯示播放 FirViewer.setSceneData(FirRoot); FirViewer.realize(); FirViewer.run(); return 0; }
5、執行結果,飛機轉圈。
6、回撥函式原型
virtual void operator() (osg::Node* node,osg::NodeVisitor* nv)
{
//需要執行的操作
traverse(node,nv);
}
7、回撥方法
setUpdatedataCallback();
setCullCallback();
setDrawCallback();
setEventCallback();
setReadFileCallback();
setWriteFileCallback();