cocos2d-x游戏开发之动画

 MyGame.h中声明动画函数:

class MyGame : public cocos2d::Layer
{
public:
 static Scene* createScene();
    void Updatetime(float t);
   virtual bool init();
   void logic(float dt);

   ........
   cocos2d::Animate* createAnimate1();
   CREATE_FUNC(MyGame);

}

MyGame.cpp:

#include "MyGame.h"

#include "cocostudio/CocoStudio.h"

#include "ui/CocosGUI.h"

#include "cocos2d.h"

#include<iostream>

using namespace std;

USING_NS_CC;

using namespace cocos2d;

using namespace cocostudio::timeline;

cocos2d::Animate* MyGame::createAnimate1() {

 auto animation = Animation::create();

 for (int i = 1; i <= 4; i++)  {   //四张图片(用于组成动画)

 animation->addSpriteFrameWithFile(StringUtils::format("run%d.png", i));

 }

 animation->setDelayPerUnit(3.0f / 15.0f);  

//回到原始状态

animation->setRestoreOriginalFrame(true);

 auto animate = Animate::create(animation);

 return animate;

}

Scene* MyGame::createScene() {

 // 'scene' is an autorelease object

 auto scene = Scene::create();

 // 'layer' is an autorelease object

 auto layer = MyGame::create();

 // add layer as a child to scene

 scene->addChild(layer);

 // return the scene  return scene; }

bool MyGame::init() {

 // 1. super init first

 if (!Layer::init())

 {  

 return false;

 }

 ball = Sprite::create("run1.png");
 ball->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
 this->addChild(ball,2);

//点击btn0,则运行击打棒球动画

btn0->addClickEventListener([&](Ref* pSender) {
  ball->runAction(createAnimate1());
 });

return true;

}

注意:若按钮事件中包含切换场景事件,则需要在按钮事件中添加schedule函数,否则切换场景后,动画还来不及生成,再次点击按钮出发按钮事件,则动画不会执行,即无反应

具体代码如下:

//为按钮添加触摸事件
 btn0->addTouchEventListener([&, btn0, btn1, btn2](Ref* pSender, Widget::TouchEventType type) {
  switch (type)
  {
  case Widget::TouchEventType::BEGAN:
   btn0->setScale(1.02);
   break;
  case Widget::TouchEventType::ENDED:
   btn0->setScale(1);
   btn1->setTouchEnabled(false);
   btn2->setTouchEnabled(false);
   .......


   if (r[0] == 3 || delegate1->restartnum == 0)
   {
   ..........

  //切换场景时不能单单写一句代码 Director::getInstance()->replaceScene(GameOver::createScene());

  //而应该写个schedule函数用于缓冲时间


    schedule([&](float ft) {
     unschedule("GameOver");
     Director::getInstance()->replaceScene(GameOver::createScene());
    },1,0,0,"GameOver");
   }
   else
    schedule([&](float ft) {
    unschedule("newGame");
    Director::getInstance()->replaceScene(MyGame::createScene());
   },1, 0, 0, "newGame");
   }
  });

原文地址:https://www.cnblogs.com/lchzls/p/5027201.html