osg 标准视图、前视图、侧视图、顶视图切换

 

 

#include <osg/Node>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osgViewer/Viewer>
#include <osgGA/GUIEventHandler>

// 自定义的视图切换事件处理器
class ViewSwitchHandler : public osgGA::GUIEventHandler {
public:
    ViewSwitchHandler(osg::ref_ptr<osg::Camera> camera) : _camera(camera) {}

    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&) override {
        switch (ea.getEventType()) {
            case osgGA::GUIEventAdapter::KEYDOWN:
                switch (ea.getKey()) {
                    case '1': // 标准视图
                        _camera->setViewMatrixAsLookAt(osg::Vec3(0, 0, 10), osg::Vec3(0, 0, 0), osg::Vec3(0, 1, 0));
                        return true;
                    case '2': // 前视图
                        _camera->setViewMatrixAsLookAt(osg::Vec3(0, 0, -10), osg::Vec3(0, 0, 0), osg::Vec3(0, 0, -1));
                        return true;
                    case '3': // 侧视图
                        _camera->setViewMatrixAsLookAt(osg::Vec3(10, 0, 0), osg::Vec3(0, 0, 0), osg::Vec3(1, 0, 0));
                        return true;
                    case '4': // 顶视图
                        _camera->setViewMatrixAsLookAt(osg::Vec3(0, 10, 0), osg::Vec3(0, 0, 0), osg::Vec3(0, 0, 1));
                        return true;
                }
        }
        return false;
    }

private:
    osg::ref_ptr<osg::Camera> _camera;
};

int main() {
    // 创建一个场景图
    osg::ref_ptr<osg::Group> root = new osg::Group;
    osg::ref_ptr<osg::Geode> geode = new osg::Geode;
    osg::ref_ptr<osg::ShapeDrawable> drawable = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, 0), 1, 1, 1));
    geode->addDrawable(drawable);
    root->addChild(geode);

    // 创建一个相机
    osg::ref_ptr<osg::Camera> camera = new osg::Camera;
    camera->setViewMatrixAsLookAt(osg::Vec3(0, 0, 10), osg::Vec3(0, 0, 0), osg::Vec3(0, 1, 0));
    camera->setProjectionMatrixAsPerspective(30.0, static_cast<double>(800) / 600.0, 1.0, 1000.0);
    root->addChild(camera);

    // 创建一个视图器
    osgViewer::Viewer viewer;
    viewer.setSceneData(root);

    // 添加视图切换事件处理器
    viewer.addEventHandler(new ViewSwitchHandler(camera));

    // 运行视图器
    return viewer.run();
}

 

 

 

 

 

========

posted @ 2024-04-08 23:31  西北逍遥  阅读(145)  评论(0编辑  收藏  举报