OSG控制漫游

编写一个类来做控制器:分别实现WSAD上下左右功能:

#pragma once
#include "../Common.h"

class TravelManipulator :public osgGA::CameraManipulator {
public:
    TravelManipulator();
    ~TravelManipulator();

public:
    //设置当前视口
    virtual void setByMatrix(const osg::Matrixd&matrix);

    //设置当前视口
    virtual void setByInverseMatrix(const osg::Matrixd&matrix);

    //得到当前矩阵
    virtual osg::Matrixd getMatrix() const;

    //得到当前矩阵
    virtual osg::Matrixd getInverseMatrix() const;

    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us);
private:
    //视点
    osg::Vec3 mPosition;
    //朝向
    osg::Vec3 mRotation;

    //移动步长
    int mStep;
    //旋转步长
    float mRotateStep;
}; 
#include "TravelManipulator.h"


TravelManipulator::TravelManipulator() {
    mPosition = osg::Vec3(0, 0, 50);
    mRotation = osg::Vec3(0, 0, 0);
    mStep = 0;
    mRotateStep = 0.0;
}

TravelManipulator::~TravelManipulator() {
}

void TravelManipulator::setByMatrix(const osg::Matrixd&matrix) {

}

void TravelManipulator::setByInverseMatrix(const osg::Matrixd&matrix) {

}

osg::Matrixd TravelManipulator::getMatrix() const {
    osg::Matrixd mat;
    mat.makeTranslate(mPosition);
    return mat * osg::Matrixd::rotate(mRotation[0], osg::X_AXIS, mRotation[1], osg::Y_AXIS, mRotation[2], osg::Z_AXIS);
}

osg::Matrixd TravelManipulator::getInverseMatrix() const {
    osg::Matrixd mat;
    mat.makeTranslate(mPosition);
    return osg::Matrixd::inverse(mat * osg::Matrixd::rotate(mRotation[0], osg::X_AXIS, mRotation[1], osg::Y_AXIS, mRotation[2], osg::Z_AXIS));
}

bool TravelManipulator::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us) {
    switch (ea.getEventType()) {
    case osgGA::GUIEventAdapter::KEYDOWN:
    if (ea.getKey()=='w'){
        mPosition[2] += 2;
    } else if (ea.getKey() == 's') {
        mPosition[2] -= 2;
    } else if (ea.getKey() == 'a') {
        mPosition[0] -= 2;
    } else if (ea.getKey() == 'd') {
        mPosition[0] += 2;
    }
    break;
    default:
    break;
    }
    return false;
}

调用:

int main(int argc, char** argv) {
    for (int i = 0; i < argc; i++) {
        printf(argv[i]);
        printf("\n");
    }

    osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();


    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
    viewer->addEventHandler(new osgViewer::StatsHandler);

    osg::ref_ptr<osg::Group> root = new osg::Group;

    root->addChild(osgDB::readNodeFile("xyz.osgt")); 

    viewer->setSceneData(root);

    viewer->setCameraManipulator(new TravelManipulator());//关键
    viewer->realize();
    viewer->run();

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wb175208

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值