Cocos2dx_有限状态机_1

#ifndef __MONKEY_H__
#define __MONKEY_H__

#include "cocos2d.h"
#include <time.h>

using namespace std;
using namespace cocos2d;

#define MAX_STOP_TIME  10
#define MAX_WALK_TIME  20

#define MAX_WALK_DIST  100 

enum MonkeyState
{
	stStop,
	stWalk,
	stTrun,
};

class Monkey : public Node
{
public:
	Monkey();
	CREATE_FUNC(Monkey);

	//override
	virtual bool init();
	virtual void update(float delta);

	void changeState(MonkeyState newState);
	void stop();
	void walk();
	void trun();

	bool isStopTimeOut();
	bool isWalkTimeOut();
	bool isWalkOutBorder();
private:
	Sprite* sp;
	MonkeyState _curState;
	time_t _curTime;

	int _curPos;
	int _curStep;
};

#endif
#include "Monkey.h"

Monkey::Monkey()
{
}

bool Monkey::init()
{
	if (!Node::init())
	{
		return false;
	}

	this->_curPos = 0;
	this->_curStep = 1;
	this->_curState = NULL;

	this->changeState(MonkeyState::stStop);
	this->scheduleUpdate();

	this->sp = Sprite::create("eraser.png");
	sp:setPosition(Vec2(0, 0));
	this->addChild(this->sp);

	return true;
}

void Monkey::update(float delta)
{
	switch(this->_curState)
	{
		case stStop:
			if (this->isStopTimeOut())
			{
				this->changeState(MonkeyState::stWalk);
				this->walk();
			}
			break;
		case stWalk:
			this->walk();
			if (this->isWalkOutBorder())
			{
				this->changeState(MonkeyState::stTrun);
				this->trun();
			}
			else if (this->isWalkTimeOut())
			{
				this->changeState(MonkeyState::stStop);
				this->stop();
			}
			break;
		case stTrun:
			this->changeState(MonkeyState::stWalk);
			this->walk();
			break;
	}
}

void Monkey::changeState(MonkeyState newState)
{
	this->_curState = newState;
	this->_curTime = time(0);
}

void Monkey::stop()
{
	log("stop()");
}

void Monkey::walk()
{
	this->_curPos += this->_curStep;
	this->sp->setPosition(Vec2(this->_curPos*0.5, 0));
	log("walk(): pos=%d", this->_curPos);
}

void Monkey::trun()
{
	this->_curStep *= -1;
	log("turn(): step=%d", this->_curStep);
}

bool Monkey::isStopTimeOut()
{
	return (time(0) - this->_curTime > MAX_STOP_TIME);
}

bool Monkey::isWalkTimeOut()
{
	return (time(0) - this->_curTime > MAX_WALK_TIME);
}

bool Monkey::isWalkOutBorder()
{
	return (this->_curPos > MAX_WALK_DIST || this->_curPos < -MAX_WALK_DIST);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值