【cocos2dx 3.2】一个都不能死2 人物层

分析:

  1. 人物对象看作是一个Sprite类
  2. Sprite类里面有:texture,action,physics属性
  3. 人物不断重复跑步的动画可以用action实现
  4. 人物不会掉落下边界,应该设置物理边界

分析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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值