cocos2d-x开发初体验

动画帧工具类

ActionTool.h

#pragma once
#ifndef ActionTool_H__
#define ActionTool_H__

#include "cocos2d.h"
USING_NS_CC;

class ActionTool {
public:
    //无帧数量创建动画
    static Animate* animationWithFrameName(const char *frameName, int iloops, float delay);
    //有帧数量创建动画
    static Animate* animationWithFrameAndNum(const char *frameName, int num, float delay);

};
#endif // !ActionTool_H__s

ActionTool.cpp

  • 引用头文件

    #include "ActionTool.h"
  • 无帧数量创建动画

    Animate* ActionTool::animationWithFrameName(const char *each_name, int iloops, float delay)
    {
      SpriteFrame* frame = NULL;
      Animation* animation = Animation::create();
      int index = 1;
      //遍历所有可执行帧
      do {
          //通过名字来获取动画帧
          String *name = String::createWithFormat("%s%d",each_name,index++);
    
          frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
          if (frame == NULL) {
              break;
          }
          animation->addSpriteFrame(frame);
      } while (true);
      animation->setDelayPerUnit(delay);
      animation->setRestoreOriginalFrame(true);
      Animate* animate = Animate::create(animation);
      return animate;
    }
  • 有帧数量创建动画

    Animate* ActionTool::animationWithFrameAndNum(const char *frameName, int framecount, float delay) {
      SpriteFrame* frame = NULL;
      Animation* animation = Animation::create();
      int index = 1;
      for (int index = 1; index <= framecount; index++) {
          String *name = String::createWithFormat("%s%d", frameName, index++);
          frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
          animation->addSpriteFrame(frame);
      }
      animation->setDelayPerUnit(delay);
      animation->setRestoreOriginalFrame(true);
      Animate* animate = Animate::create(animation);
      return animate;
    
      /*第二种方法
      //向量
      Vector<SpriteFrame*>animFrames;
      char str[20];
      for (int k = 1; k <= framecount; k++) {
          sprintf(str , "%s%d.png",frameName , k);
          SpriteFrame *frame = SpriteFrameCache::getInstance()->spriteFrameByName(str);
          animFrames.pushBack(frame);
      }
      return Animate::create(Animation::createWithSpriteFrames(animFrames, delay));
      */
    }
添加新评论