加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Cocos2dx_有限状态机_1

发布时间:2020-12-14 16:30:47 所属栏目:百科 来源:网络整理
导读:#ifndef __MONKEY_H__#define __MONKEY_H__#include "cocos2d.h"#include time.husing 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
#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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读