- Cocos2d-x by Example:Beginner's Guide(Second Edition)
- Roger Engelbert
- 310字
- 2021-07-23 20:00:28
Time for action – coding the GameLayer interface
GameLayer
is the main container in our game.
- Follow the steps to add a new file to your
Classes
folder. This is a C++ file calledGameLayer
. - Select your
GameLayer.h
. Just below the firstdefine
preprocessor command, add:#define GOAL_WIDTH 400
- We define the width of the goals in pixels.
- 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-xVector
. We also have two text labels to display the score for each player. - Declare a variable to store the screen size. We'll use this a lot for positioning:
Size _screenSize;
- Add variables to store the score information and a method to update these scores on screen:
int _player1Score; int _player2Score; void playerScore (int player);
- 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.
- Mastering Concurrency in Go
- Kotlin Standard Library Cookbook
- 用Flutter極速構(gòu)建原生應(yīng)用
- Instant RubyMotion App Development
- 微信小程序項(xiàng)目開發(fā)實(shí)戰(zhàn)
- Learning OpenStack Networking(Neutron)
- Java EE核心技術(shù)與應(yīng)用
- R語(yǔ)言數(shù)據(jù)可視化:科技圖表繪制
- 運(yùn)維前線:一線運(yùn)維專家的運(yùn)維方法、技巧與實(shí)踐
- Java并發(fā)編程之美
- Learning Nessus for Penetration Testing
- Node.js區(qū)塊鏈開發(fā)
- Java7程序設(shè)計(jì)入門經(jīng)典
- Java Web開發(fā)教程:基于Struts2+Hibernate+Spring
- ANSYS FLUENT 16.0超級(jí)學(xué)習(xí)手冊(cè)