作业要求
- 随机产生怪物并且怪物会向角色靠近
- 怪物碰到角色后,角色掉血,角色血量为空则播放死亡动画并解除所有事件
- 角色可以攻击怪物
- 使用tilemap创建地图
- 加分项:使用本地数据存储,记录打到的怪物数量,同时在游戏中显示打倒数量
游戏演示
Resources文件夹截图
TileMap软件界面截图
UserDefault.xml位置及内容截图
解决的有关问题
问题的解决方法在代码的注释中
- tmx文件无法显示问题
- UserDefault.xml文件位置问题
- 死亡动画和停止所有动画的冲突问题
具体实现
HelloWorldScene.h
#pragma once
#include "cocos2d.h"
using namespace cocos2d;
class HelloWorld : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
private:
cocos2d::Sprite* player;
cocos2d::Vector<SpriteFrame*> attack;
cocos2d::Vector<SpriteFrame*> dead;
cocos2d::Vector<SpriteFrame*> run;
cocos2d::Vector<SpriteFrame*> idle;
cocos2d::Size visibleSize;
cocos2d::Vec2 origin;
cocos2d::Label* time;
int dtime;
cocos2d::ProgressTimer* pT;
//判断是否在播放动作
bool isAnimating;
//移动
void moveCallback(Ref* pSender, std::string direction);
//攻击
void attackCallback(Ref* pSender);
//死亡
void deadCallback(Ref* pSender);
//重写update,实现倒计时
void update(float time)override;
//下面是新加的变量
//用来显示打倒的敌人数
cocos2d::Label* score;
//判断是否在攻击
bool isAttack = false;
//判断是否在死亡
bool isDead = false;
//产生一个怪物,并且移动
void createMonster(float time);
//被怪物打击
void hitByMonster(float time);
//停止所有动作
void stop(float time);
};
HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "Monster.h"
//宏定义用于本地数据持久化
#define database UserDefault::getInstance()
//因为string要用,或者std::string也行
using namespace std;
#pragma execution_character_set("utf-8")
USING_NS_CC;
Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}
// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
printf("Error while loading: %s\n", filename);
printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//
// 1. super init first
if ( !Scene::init() )
{
return false;
}
visibleSize = Director::getInstance()->getVisibleSize();
origin = Director::getInstance()->getVisibleOrigin();
//这里需要特别注意
/***********************************************************************/