分析:
- 人物对象看作是一个Sprite类
- Sprite类里面有:texture,action,physics属性
- 人物不断重复跑步的动画可以用action实现
- 人物不会掉落下边界,应该设置物理边界
分析Json图片类(plter提供)
3.2以上的需要把Vec2换成Point,ValueMapNull换成ValueMap
FlashTool.h
#ifndef __NoOneDies__FlashTool__
#define __NoOneDies__FlashTool__
#include <iostream>
#include <cocos2d.h>
USING_NS_CC;
class FlashTool {
public:
static Animate * readJsonSpriteSheet(std::string jsonFile,float delayPerUnit);
};
#endif /* defined(__NoOneDies__FlashTool__) */
FlashTool.cpp
#include "FlashTool.h"
#include "json/document.h"
Animate * FlashTool::readJsonSpriteSheet(std::string jsonFile,float delayPerUnit){
rapidjson::Document doc;
std::string fileContent = FileUtils::getInstance()->getStringFromFile(jsonFile);
fileContent.erase(0,fileContent.find_first_of('{'));
doc.Parse<0>(fileContent.c_str());
std::string imgFileName = doc["meta"]["image"].GetString();
auto &frames = doc["frames"];
auto sfc = SpriteFrameCache::getInstance();
Vector<AnimationFrame*> animFrames;
for (auto m=frames.MemberonBegin(); m!=frames.MemberonEnd(); m++) {
auto frameName = m->name.GetString();
auto & frameProperties = m->value["frame"];
auto & spriteSourceSize = m->value["spriteSourceSize"];
auto sf = sfc->getSpriteFrameByName(frameName);
if (!sf) {
sf = SpriteFrame::create(imgFileName, Rect(frameProperties["x"].GetInt(), frameProperties["y"].GetInt(), frameProperties["w"].GetInt(), frameProperties["h"].GetInt()), m->value["rotated"].GetBool(), Point(spriteSourceSize["x"].GetInt(), spriteSourceSize["y"].GetInt()), Size(spriteSourceSize["w"].GetInt(), spriteSourceSize["h"].GetInt()));
sfc->addSpriteFrame(sf, frameName);
}
ValueMap ValueMapNull;
animFrames.pushBack(AnimationFrame::create(sf, delayPerUnit, ValueMapNull));
}
Animation * animation = Animation::create(animFrames,delayPerUnit);
return Animate::create(animation);
}
Hero.h
#include "cocos2d.h"
#include "FlashTool.h"
USING_NS_CC;
class Hero : public Sprite
{
public:
//创建create方法,自动调用init和返回Hero类
virtual bool init();
CREATE_FUNC(Hero);
};
Hero.cpp
#include"Hero.h"
USING_NS_CC;
bool Hero::init()
{
//执行父类的初始化方法
Sprite::init();
//根据图片大小定义人物的宽高
Size size = Size(44,52);
setContentSize(size);
//设置人物的物理属性
setPhysicsBody(PhysicsBody::createBox(size));
//设置人物的动作
runAction(RepeatForever::create(FlashTool::readJsonSpriteSheet("hero.json",0.2f)));
//设置碰撞标记,使其能触发碰撞监听
getPhysicsBody()->setContactTestBitmask(1);
//防止碰撞时的翻转
getPhysicsBody()->setRotationEnable(false);
return true;
}