在游戏开发中,有时会须要在某个游戏对象上的运动轨迹上实现渐隐效果。比方子弹的运动轨迹,假设不借助引擎的帮助,这样的效果则须要通过大量的图片来实现。而Cocos2D-x的拖动渐隐效果类CCMotionStreak就帮助我们实现这个效果。以下是子弹飞行火焰拖尾的效果实现。。
[cpp] view
plaincopy
plaincopy
- #include "HelloWorldScene.h"
- #include "SimpleAudioEngine.h"
- using namespace cocos2d;
- using namespace CocosDenshion;
- CCScene* HelloWorld::scene()
- {
- CCScene *scene = CCScene::create();
- HelloWorld *layer = HelloWorld::create();
- scene->addChild(layer);
- return scene;
- }
- bool HelloWorld::init()
- {
- if ( !CCLayer::init() )
- {
- return false;
- }
- size = CCDirector::sharedDirector()->getWinSize();
- CCLayerColor* background = CCLayerColor::create(ccc4(255, 200, 255, 255), size.width, size.height);
- this->addChild(background);
- //存储子弹节点
- bulltArr = CCArray::create();
- CC_SAFE_RETAIN(bulltArr);
- //存储 CCMotionStreak
- streakArr = CCArray::create();
- CC_SAFE_RETAIN(streakArr);
- scheduleUpdate();
- return true;
- }
- void HelloWorld::update(float delta)
- {
- for (int i = 0; i < bulltArr->count(); i++) {
- CCSprite* bullt = (CCSprite*)bulltArr->objectAtIndex(i);
- bullt->setPositionY(bullt->getPositionY()+2);
- CCMotionStreak* streak = (CCMotionStreak*)streakArr->objectAtIndex(i);
- //每次调用setPosition函数又一次设置对象位置时,“影子”将被创建而且慢慢渐隐 注:对于CCMotionStreak对象不可用getPosition()等方法。。
- streak->setPosition(bullt->getPosition());
- }
- for (int i = 0; i < bulltArr->count(); i++) {
- CCSprite* bullt = (CCSprite*)bulltArr->objectAtIndex(i);
- //删除超出屏幕节点
- if (bullt->getPositionY() >= size.height+bullt->getContentSize().height) {
- this->removeChild(bullt);
- bulltArr->removeObject(bullt);
- CCSprite* streak = (CCSprite*)streakArr->objectAtIndex(i);
- this->removeChild(streak);
- streakArr->removeObject(streak);
- break;
- }
- }
- }
- //拖尾效果类CCMotionStreak
- //创建 子弹节点 和 CCMotionStreak对象
- void HelloWorld::createBullt(CCPoint startPoint)
- {
- CCSprite* bullt = CCSprite::create("bullet3.png");
- bullt->setPosition(startPoint);
- this->addChild(bullt,2);
- bulltArr->addObject(bullt);
- //第一个參数是间隐的时间,第二个參数是间隐片断的大小,第三个參数是贴图的宽高,第四个參数是颜色值RGB,第五个參数是贴图的路径或者贴图对象
- CCMotionStreak* streak = CCMotionStreak::create(0.8, 10, 10, ccRED, "bullet3.png");
- streak->setPosition(startPoint);
- this->addChild(streak,1);
- streakArr->addObject(streak);
- }
- bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
- {
- createBullt(pTouch->getLocation());
- return true;
- }
- void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent){}
- void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent){}
- void HelloWorld::onEnter()
- {
- CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, false);
- CCLayer::onEnter();
- }
- void HelloWorld::onExit()
- {
- CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
- CCLayer::onExit();
- }
- HelloWorld::~HelloWorld()
- {
- CC_SAFE_RELEASE(bulltArr);
- CC_SAFE_RELEASE(streakArr);
- }
很多其它0