5.2.4.跃动的线

该代码示例展示了如何在osg中创建一个动态更新的线段。通过DynamicLineCallback类实现线段顶点的更新,以模拟线的移动。程序创建了一个线性条带,并设置了更新回调以改变最后一顶点的位置,产生动态效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <osg/LineWidth>
#include <osg/Geometry>
#include <osg/Geode>
#include <osgViewer/Viewer>

class DynamicLineCallback : public osg::Drawable::UpdateCallback
{
public:
    DynamicLineCallback() : _angle(0.0)
    {

    }

    virtual void update(osg::NodeVisitor* nv, osg::Drawable*drawable)
    {
        osg::Geometry* geom = dynamic_cast<osg::Geometry*>(drawable);
        if (!geom)
        {
            return;
        }

        osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geom->getVertexArray());
        if (vertices)
        {
            for (osg::Vec3Array::iterator itr = vertices->begin(); itr != vertices->end() - 1; ++itr)
            {
                itr->set(*(itr + 1));
            }

            _angle += 1.0 / 10.0;
        }

        osg::Vec3& pt = vertices->back();
        pt.set(10.0 * cos(_angle), 0.0, 10.0 * sin(_angle));
        vertices->dirty();
    }
private:
    float _angle;
};
int main(int argc, char *argv[])
{
    osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(10);
    for (unsigned int i = 0; i < 10; ++i)
    {
        (*vertices)[i].set(float(i), 0.0, 0.0);
    }

    osg::ref_ptr<osg::Geometry> lineGeom = new osg::Geometry;
    lineGeom->setVertexArray(vertices.get());
    lineGeom->addPrimitiveSet(new osg::DrawArrays(osg::DrawArrays::LINE_STRIP, 0, 10));
    lineGeom->setInitialBound(osg::BoundingBox(osg::Vec3(-10, -10, -10), osg::Vec3(10, 10, 10)));
    lineGeom->setUpdateCallback(new DynamicLineCallback);
    lineGeom->setUseDisplayList(false);
    lineGeom->setUseVertexBufferObjects(true);

    osg::ref_ptr<osg::Geode> geode = new osg::Geode;
    geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    geode->getOrCreateStateSet()->setAttribute(new osg::LineWidth(2.0));
    geode->addDrawable(lineGeom.get());

    osgViewer::Viewer viewer;
    viewer.setSceneData(geode.get());
    return viewer.run();

}

效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值