1. 程式人生 > >cocos2d-x 3.0 動畫與觸控事件總結

cocos2d-x 3.0 動畫與觸控事件總結

動畫與觸控

動畫

動畫分為兩部分  animation   animate  

將動畫類比為連環畫,則 animation相當於造書的過程而 animate則為快速翻書的動作通常會再新增一個repeateForever的動作,確保動畫一直繼續下去

1️⃣animation 首先建立精靈幀快取,然後將許多圖片合成一張大圖片與plist檔案,加入快取中

   // 建立獲取精靈幀快取

    auto cache = SpriteFrameCache::getInstance();

    // 從檔案中讀取精靈幀,加入精靈幀快取中

    cache->addSpriteFramesWithFile("fish.plist","fish.png");

2️⃣然後建立一個容器用來存放animation,即將一頁頁的圖片放入建冊成書

Vector<SpriteFrame *>vec; // 建立一個容器

    char str[20]; // 用來儲存圖片名稱

    for (int i=1; i<22; i++) {

        // 將圖片名稱儲存到str

        sprintf(str, "fish_%d.png",i);

        // 通過圖片名獲取精靈幀

        auto frame = cache->getSpriteFrameByName(str);

        // 將獲取的精靈幀加入容器

        vec.pushBack(frame);

    }

    // 通過容器vec建立動畫

    auto animation = Animation::createWithSpriteFrames(vec);

    // 設定幀間隔

    animation->setDelayPerUnit(0.1);

3️⃣然後就是根據連環畫書建立animate動作

auto animate = Animate:: create(animation);// 通過動畫建立動作

4️⃣設定首頁   開始動畫

// 通過精靈幀建立精靈sp

    auto fream = cache->getSpriteFrameByName("fish_1.png");

    auto sp = Sprite::createWithSpriteFrame(fream);

//  精靈的常見設定

    sp->setPosition(480, 320);

    addChild(sp);

    sp->runAction(repate);

觸控

觸控動作的實現(多點觸控基本類似)

1️⃣首先要重寫父類的觸控事件

 //重寫Layer的四個觸控事件的函式(不是必須全部重寫,但第一個必須要寫,因為在觸控開始的基礎上才會有後續的動作,哪怕它為空)

    virtual bool onTouchBegan(Touch *touch, Event *unused_event)override;

    virtual void onTouchMoved(Touch *touch, Event *unused_event)override;

    virtual void onTouchEnded(Touch *touch, Event *unused_event)override;

    virtual void onTouchCancelled(Touch *touch, Event *unused_event)override;

2️⃣init函式中設定監聽器與事件分發器

     //   auto listener = EventListenerTouchAllAtOnce::create();  多點觸控的監聽

    // 建立一個單點觸控的監聽

    auto lisstener = EventListenerTouchOneByOne::create();

    // 指定監聽的觸控事件的回撥函式

    lisstener->onTouchBegan = CC_CALLBACK_2(touchTest::onTouchBegan, this);// this 表示layer

    lisstener->onTouchMoved= CC_CALLBACK_2(touchTest::onTouchMoved, this);

    lisstener->onTouchEnded= CC_CALLBACK_2(touchTest::onTouchEnded, this);

    lisstener->onTouchCancelled= CC_CALLBACK_2(touchTest::onTouchCancelled, this);

    // 獲取事件分發器

    auto dispatcher = Director::getInstance()->getEventDispatcher();

   // 用事件分發器設定監聽器與監聽的物件

   // 注意:一個監聽器只能監聽一個物件,可以使用克隆方法,類似於action的克隆  lisstener->clone()

    dispatcher->addEventListenerWithSceneGraphPriority(lisstener, this);

3️⃣重寫觸控事件(實現)

void touchTest:: onTouchMoved(Touch *touch, Event *unused_event){

    // 獲取觸發觸控事件的目標

    auto target =dynamic_cast<Sprite *>(unused_event->getCurrentTarget());

   // 獲得當前觸控點的位置

    auto point = touch->getLocation();

    // 獲取上一次函式呼叫時的觸控點的位置

    auto prepoint = touch->getPreviousLocation();

    // 獲取觸控物件的Rect

    auto rect = target->getBoundingBox();

    if(rect.containsPoint(prepoint)){

        // 目標隨著觸控點的移動而移動

        target->setPosition(point);

        //

    }

}

思考:觸控事件與按鈕繫結事件的區別與聯絡

不同:按鈕可以跳轉場景,在兩個場景間操作,而觸控事件更多強調的是在當前場景下的操作,

觸控是否繼承自按鈕動作