本章内容需用到C++11中的function,之前的一个博文专门介绍了其用法,在此不再赘述。
当开发一个rpg游戏,有一个非常重要的元素就是事件。事件的触发才能推动游戏的进行。在这里我通过使用function和cocos2dx来实现事件的回调,模拟一个简单的rpg游戏事件触发。
首先我们定义一个类EventNode
#ifndef Event_cpp
#define Event_cpp
#include <stdio.h>
#include "cocos2d.h"
using namespace::cocos2d;
class EventNode : public Node{
public:
EventNode(int id);
std::function<void (void)> callback;//回调方法
virtual void onEnter();
virtual void update(float dt);
void setEvent( std::function<void (void)> callback);
int id;
Size size ;
virtual Rect getBoundingBox();
};
#endif /* Event_cpp */
类的实现:
#include "EventNode.hpp"
#include "Global.h"// 全局单例,里面有player
EventNode::EventNode(int id){
this->id = id;
size = Size(32,32);
this->callback = [](){
log("event not init");
};//回调事件初始化
}
void EventNode::onEnter(){
Node::onEnter();
scheduleUpdate();
}
void EventNode::setEvent( std::function<void (void)> callback){
this->callback = callback;
}
void EventNode::update(float dt){
if (this->getBoundingBox().containsPoint( global->player->getPosition())) {
callback();//当玩家碰撞到该事件体,执行回调
}
}
Rect EventNode::getBoundingBox(){
return Rect(this->getPositionX()-size.width/2,
this->getPositionY()-size.height/2,
size.width,size.height);//定义碰撞范围
}
该类有一个构造函数,需要传递一个id,这样是为了方便我们在之后找到它。
接下来我们该如何使用呢?
首先我们在游戏场景中先加入一个EventNode。
EventNode * eventnode = new EventNode(1);
eventnode->setPosition(Vec2(x,y));
eventLayer->addChild(eventnode);//eventLayer是事件层。在场景中
接下来我们定义一个寻找事件点的方法
EventNode * getEventById(int id){
EventNode * event;
Vector<Node *> nodes = eventLayer->getChildren();
for (auto node :nodes) {
EventNode * tmp = (EventNode *)node;
if (tmp->id==id) {
event = tmp;
log("event is find ! id:%d",id);
}
}
return event;
}
我们通过该方法对事件点的回调进行修改,修改成我们想要其发生的事件。
EventNode * event = getEventById(1);
event->setEvent([](){
log("修改的事件");
});
这样我们就成功地在游戏场景中添加了一个事件,这样我们的玩家可以在碰撞到该事件点执行事件。当然我们还有很多种触发方式,在代码中修改也是非常容易的。