cocos2d-x 简单实现RPG游戏中的事件触发(C++)

来源:互联网 发布:网络摄像头的ip自适应 编辑:程序博客网 时间:2024/05/29 12:30

本节内容需用到C++11中的function,之前的一个博文专门介绍了其用法,在此不再赘述。

当开发一个rpg游戏,有一个非常重要的元素就是事件。事件的触发才能推动游戏的进行。在这里我通过使用function和cocos2dx来实现事件的回调,模拟一个简单的rpg游戏事件触发。

首先我们定义一个类EventNode 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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 */

类的实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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。

?
1
2
3
EventNode * eventnode = new EventNode(1);
eventnode->setPosition(Vec2(x,y));
eventLayer->addChild(eventnode);//eventLayer是事件层。在场景中

接下来我们定义一个寻找事件点的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}

我们通过该方法对事件点的回调进行修改,修改成我们想要其发生的事件。

?
1
2
3
4
5
EventNode * event = getEventById(1);
 
    event->setEvent([](){
        log("修改的事件");
    });

这样我们就成功地在游戏场景中添加了一个事件,这样我们的玩家可以在碰撞到该事件点执行事件。当然我们还有很多种触发方式,在代码中修改也是非常容易的。

0 0