官术网_书友最值得收藏!

Time for action – coding the GameLayer interface

GameLayer is the main container in our game.

  1. Follow the steps to add a new file to your Classes folder. This is a C++ file called GameLayer.
  2. Select your GameLayer.h. Just below the first define preprocessor command, add:
    #define GOAL_WIDTH 400
  3. We define the width of the goals in pixels.
  4. Next, add the declarations for our sprites and our score text labels:
    #include "cocos2d.h"
    #include "GameSprite.h"
    
    using namespace cocos2d;
    
    class GameLayer : public Layer
    {
        GameSprite* _player1;
        GameSprite* _player2;
        GameSprite* _ball;
        
        Vector<GameSprite*> _players;
        Label* _player1ScoreLabel;
        Label* _player2ScoreLabel;

    We have the GameSprite objects for two players (the weird looking things called mallets), and the ball (called a puck). We'll store the two players in a Cocos2d-x Vector. We also have two text labels to display the score for each player.

  5. Declare a variable to store the screen size. We'll use this a lot for positioning:
    Size _screenSize;
  6. Add variables to store the score information and a method to update these scores on screen:
    int _player1Score;
    int _player2Score;
        
    void playerScore (int player);
  7. Finally, let's add our methods:
    public:
        
       GameLayer();
       virtual ~GameLayer();
       virtual bool init();
    
        static Scene* scene();
        
        CREATE_FUNC(GameLayer);
        
        void onTouchesBegan(const std::vector<Touch*> &touches,  Event* event);
       void onTouchesMoved(const std::vector<Touch*> &touches,  Event* event);
       void onTouchesEnded(const std::vector<Touch*> &touches,  Event* event);
    
      void update (float dt);
    };
    #endif // __GAMELAYER_H__

There are constructor and destructor methods, then the Layer init methods, and finally the event handlers for the touch events and our loop method called update. These touch event handlers will be added to our class to handle when users' touches begin, when they move across the screen, and when they end.

What just happened?

GameLayer is our game. It contains references to all the sprites we need to control and update, as well as all game data.

In the class implementation, all the logic starts inside the init method.

主站蜘蛛池模板: 阿坝县| 遵义县| 合山市| 西盟| 黑河市| 盐城市| 铁岭市| 巴彦淖尔市| 光山县| 鹤岗市| 抚宁县| 霍林郭勒市| 仙游县| 温泉县| 博罗县| 蒙山县| 长岛县| 鲜城| 涪陵区| 四川省| 泰和县| 平泉县| 南华县| 定兴县| 铜梁县| 油尖旺区| 贵阳市| 南陵县| 琼结县| 大厂| 乳山市| 雷州市| 舞阳县| 色达县| 永济市| 阜南县| 肇源县| 洛宁县| 阳山县| 昭通市| 大渡口区|