|
- class KeyboardHandler : public osgGA::GUIEventHandler
- {
- public:
- KeyboardHandler() : _x(0.0),_y(0.0),_z(0.0) {}
- ~KeyboardHandler() {}
-
- virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*)
- {
- osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
- if (!viewer)
- {
- return false;
- }
- switch(ea.getEventType())
- {
- case osgGA::GUIEventAdapter::KEYDOWN:
- if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Space)
- {
- int width = ea.getWindowWidth();
- int height = ea.getWindowHeight();
- viewer->requestWarpPointer(width*0.5,height*0.5);
- std::cout<<"Space Down"<<std::endl;
- }
- else
- {
- osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*>(viewer->getSceneData());
- if (!pat)
- {
- return false;
- }
-
- _x += 0.7;
- _z += 0.7;
-
- osg::Vec3d trans(0.0,0.0,0.0);
-
- if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Up )
- {
- trans.set(trans.x(),trans.y(),trans.z()+_z);
- pat->setPosition(trans);
- //viewer->getCamera()->setViewMatrix(trans);
-
- std::cout<<"Up"<<std::endl;
- }
- else if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Down )
- {
- trans.set(trans.x(),trans.y(),trans.z()-_z);
- pat->setPosition(trans);
- //viewer->getCamera()->setViewMatrix(trans);
- std::cout<<"Down"<<std::endl;
- }
- else if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Left )
- {
- trans.set(trans.x()-_x,trans.y(),trans.z());
- pat->setPosition(trans);
- //viewer->getCamera()->setViewMatrix(trans);
- std::cout<<"Left"<<std::endl;
- }
- else if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Right )
- {
- trans.set(trans.x()+_x,trans.y(),trans.z());
- pat->setPosition(trans);
- //viewer->getCamera()->setViewMatrix(trans);
- std::cout<<"Right"<<std::endl;
- }
- return true;
- }
- break;
- default:break;
- }
- return false;
- }
- private:
- float _x;
- float _z;
- };
复制代码
- int main(int argc,char ** argv)
- {
- osgViewer::Viewer viewer;
- osg::Node* model = osgDB::readNodeFile( "cow.osg" );
- osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform;
- pat->addChild(model);
- viewer.setSceneData( pat.get() );
-
- viewer.addEventHandler(new KeyboardHandler);
- return viewer.run();
- }
复制代码
我按照《设计与实践》第八章那个处理键盘事件的例子,写的处理键盘事件;
通过Up,Down,Left,Right控制模型在x轴和z轴上移动;通过PositionAttitudeTransform节点控制位置变换;
出现的问题是:
按了一个键以后模型可以在一个方向上正常移动,但是再按另一个键时候,它不是从当前位置上开始移动,而又是从viewer的“零点”开始移动,请问这是为什么?求教~~~ |
|