9.4.2.物体的淡出淡入

这篇博客展示了如何使用osgAnimation库中的InOutCubicMotion类创建一个回调函数,实现在osgViewer中3D对象的渐入动画效果。通过FaderCallBack类,动态调整ShapeDrawable的透明度,使得3D Box在场景中平滑地出现和消失。

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

#include <osgViewer/Viewer>
#include <osg/Node>
#include <osg/Geode>
#include<osgAnimation/easeMotion>
#include<osg/BlendFunc>
#include<osg/ShapeDrawable>

class FaderCallBack : public osg::NodeCallback
{
public:
	FaderCallBack()
	{
		_motion = new osgAnimation::InOutCubicMotion;
	}

	virtual void operator()(osg::Node* node, osg::NodeVisitor*nv)
	{
		osg::Geode* geode = dynamic_cast<osg::Geode*>(node);
		if (nullptr == geode)
		{
			traverse(node, nv);
			return;
		}

		osg::ShapeDrawable* shape = dynamic_cast<osg::ShapeDrawable*>(geode->getDrawable(0));
		if (shape)
		{

			_motion->update(0.05); // 值越小,渐入速度越慢,人眼越有感觉;值越大,渐入速度越快,人眼察觉越困难
			float alpha = _motion->getValue();
			if (alpha > 1.0)
			{
				alpha = 2.0 - alpha;
			}

			shape->setColor(osg::Vec4(1.0, 1.0, 1.0, alpha));
		}

		traverse(node, nv);
	}

protected:
	osg::ref_ptr< osgAnimation::InOutCubicMotion> _motion;
};
int main()
{
	osg::ref_ptr<osg::ShapeDrawable>shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0, 0.0, 0.0), 1.0));
	shape->setColor(osg::Vec4(1.0, 1.0, 1.0, 1.0));
	shape->setSupportsDisplayList(false);
	osg::ref_ptr<osg::Geode> geode = new osg::Geode;
	geode->addDrawable(shape.get());
	geode->setUpdateCallback(new FaderCallBack);
	geode->getOrCreateStateSet()->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值