五毛的cocos2d-x學習筆記08-動畫,cocos2d-x08-
一個例子就夠了,單擊文本標簽,執行動畫。我也是小白,寫這個demo的時候遇到了問題,單擊文本標簽游戲就死掉了。今天為了解決這個問題也是一晚沒睡,到學習群裡問大神,經過大神的指點解決了問題。原來是Animation和Animate的生命周期的關系。先記下。

![]()
1 bool HelloWorld::init()
2 {
3 //////////////////////////////
4 // 1. super init first
5 if ( !Layer::init() )
6 {
7 return false;
8 }
9
10 SpriteFrameCache *cache = SpriteFrameCache::getInstance();
11 cache->addSpriteFramesWithFile("a6.plist");
12
13 Vector<SpriteFrame*> vec;
14 char name[15];
15 memset(name, 0, 15);
16
17 for (int i = 1; i <=7; i++){
18 sprintf(name, "a6_%02d.png", i);
19 vec.pushBack(cache->getSpriteFrameByName(name));
20 }
21
22 Animation *animation = Animation::createWithSpriteFrames(vec, 0.1f, 1);
23
24 Animate *animate = Animate::create(animation);
25
26 auto sprite = Sprite::create();
27 addChild(sprite);
28 sprite->setPosition(Vec2(200, 200));
29 //sprite->runAction(RepeatForever::create(animate));
30
31 auto label = LabelTTF::create("Touch", "Courier", 30);
32 label->setPosition(Vec2(500, 500));
33 addChild(label);
34
35 int i = 10;
36
37 EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create();
38 listener->onTouchBegan = [=](Touch *t, Event *e){
39 if (label->getBoundingBox().containsPoint(t->getLocation())){
40 //notification: pay attention to the life cycle of Animation and Animate
41 Animation *animation = Animation::createWithSpriteFrames(vec, 0.1f, 1);
42 Animate *animate = Animate::create(animation);
43 sprite->runAction(animate);
44 log("i=%d", i);
45 return true;
46 }
47 return false;
48 };
49 //notifation:here is "this" not "label" because if here is "label", Touch *t equals to "label"
50 Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);
51 return true;
52 }
init
運行效果:
