且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

《Cocos2D-x权威指南》——3.8 拖动渐隐效果类CCMotionStreak

更新时间:2022-09-27 12:52:23

3.8 拖动渐隐效果类CCMotionStreak

在游戏的实现过程中,有时会需要在某个游戏对象上的运动轨迹上实现渐隐效果。这种感觉就好像是类似飞机拉线的拖尾巴,在视觉上感觉很好,比如子弹的运动轨迹等,如果不借助引擎的帮助,这种效果往往需要通过大量的图片来实现。而Cocos2D-x提供了一种内置的拖动渐隐效果类CCMotionStreak来帮助我们实现这个效果。它是CCNode类的子类,继承关系如图3-34所示。

《Cocos2D-x权威指南》——3.8 拖动渐隐效果类CCMotionStreak


CCMotionStreak类的常用函数如表3-22所示。
《Cocos2D-x权威指南》——3.8 拖动渐隐效果类CCMotionStreak

以下示例出自tests项目中的MotionStreakTest文件夹下的MotionStreakTest.cpp文件,其中的MotionStreakTest2类如代码清单3-43所示。
代码清单3-43 定义CCMotionStreak对象

void MotionStreakTest2::onEnter()
{
    MotionStreakTest::onEnter();

    setTouchEnabled(true);

    CCSize s = CCDirector::sharedDirector()->getWinSize();
        
    streak = CCMotionStreak::create(3, 3, 64, ccWHITE, s_streak );
    addChild(streak);
    
    streak->setPosition( CCPointMake(s.width/2, s.height/2) ); 
}



void MotionStreakTest2::ccTouchesMoved(CCSet* touches, CCEvent* event)
{
    CCSetIterator it = touches->begin();
    CCTouch* touch = (CCTouch*)(*it);

    CCPoint touchLocation = touch->locationInView();    
    touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
    
    streak->setPosition( touchLocation );
}

以上代码使用create函数创建CCMotionStreak对象,每次调用setPosition函数重新设置对象位置时,“影子”将被创建并且慢慢渐隐,运行效果如图3-35所示。

《Cocos2D-x权威指南》——3.8 拖动渐隐效果类CCMotionStreak