Cocos2dx_有限状态机_1

前端之家收集整理的这篇文章主要介绍了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);
}
原文链接:https://www.f2er.com/cocos2dx/341485.html

猜你在找的Cocos2d-x相关文章