使用Cocos2d-x-3.0游戏引擎。编写一个塔防游戏 part03

Previous: http://www.cocoachina.com/bbs/read.php?tid=202683

  1. 注意!一大波代码正在靠近。

创建四对头文件和实现文件命名为“Creep”“WayPoint”“Wave”“DataModel”(或者其他你喜欢的名称,就是后面用的时候别弄混了)。把它们创建在“Class”文件夹下面而不是默认文件夹中。


Step 1

Step 2

Step3

AppDelegate— 建立窗口,载入Director和场景。

WayPoint—从瓦片地图编辑器中读取路标。

DataModel—一个数据界面,用来存储数据。

Wave—控制敌人的类型,出现速度,总数量。

Creep—坏蛋= =||

TutorialScene –用来载入地图并设定不同的参数给不同的变量。

5.1 AppDelegate

在AppDelegate.Cpp里:

只需要更改

‘auto scene = HelloWorld::createScene();’ 
```


成
‘auto scene = TutorialScene::createScene();’ 
```


我们之前已经把‘HelloWorld’ 改成了 ‘TutorialWorld’。

WayPoint:继承自“Node”。并且得到x, y的值。
 
  
See that rectangles on the map! WayPoint.

在WayPoint.h里:

#pragma once
    #include "cocos2d.h"

    USING_NS_CC;

    class WayPoint:public Node
    {
    public:
        virtual bool init();
        CREATE_FUNC(WayPoint);
    };

```


在WayPoint.cpp里:

#include "WayPoint.h"

    USING_NS_CC;

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

        return true;
    }
```







5.2 DataModel

DataModel:被用来存储游戏状态。并且我们能从任何一个类接入DataModel,通过包含它的头文件‘#include “DataModel.h” ’和下面这行代码:

DataModel *m = DataModel::getModel();

在DataModel.h里面:


   
 #pragma once
    #include "cocos2d.h"
    #include "CCVector.h"
    #include "WayPoint.h"
    #include "Creep.h"
    #include "TutorialScene.h"

    USING_NS_CC;

    class DataModel 
    {
    public:
        TutorialScene* _gameLayer;
static DataModel* getModel();
        Vector waypoints;
        Vector targets;
        Vector waves;
        //Vector towers;    // We will deal with it later.
        //Vector projectiles;  // We will deal with it later.
//GameHUD* _gameHUDLayer;  // We will deal with it later.

private:
        DataModel(){};
        static DataModel * m_pInstance;
    };
```



在DataModel.cpp里面:


#include "DataModel.h"

USING_NS_CC;
DataModel* DataModel::m_pInstance;
    DataModel* DataModel::getModel()
    {
        if (m_pInstance == NULL)
{
            m_pInstance = new DataModel();
        }
return m_pInstance;
    }
```



这个类包含了这款游戏的所有元素和特征,目标(敌人)和我们的塔(小精灵),即将使用的子弹,用来指路的路标和攻击的波数。 并且类“Wave”控制敌人的类型,出生速度和总数。



  

未完待续~(一日一更)




Next: http://www.cocoachina.com/bbs/read.php?tid=203063

24个赞 15个字

楼主威武啊!谢谢分享

楼主好!:2::2::2:

GameHUD* _gameHUDLayer;
这个是在哪里赋值的? 后面好像没有说哦
结果后面触摸响应时。。这个是空的 报错

教程part06里面,也就是后面的教程是在继续完成这个GameHUD