Book Image

Cocos2d-X by Example Beginner's Guide

By : Roger Engelbert
Book Image

Cocos2d-X by Example Beginner's Guide

By: Roger Engelbert

Overview of this book

<p>Cocos2d-x is the C++ port of arguably the most popular open source 2D framework in the world. Its predecessor was limited to the Apple family but with Cocos2d-x you can take your applications to all major app stores, with minimum extra work. Give your games a larger target audience with almost no extra hassle.<br /><br />"Cocos2d-X by Example Beginner's Guide" allows you to build your own cross platform games using all the benefits of a time tested framework, plus the elegance and simplicity of C++.</p> <p>Each of the six games developed in this book will take you further on the road to becoming an expert game developer with no fuss and plenty of fun.<br /><br />Follow six tutorials for six very different games that leverage the ease of Cocos2D-X and its quick implementation, moving from simple ideas to more advanced topics in game development.</p> <p>In easy-to-follow steps, the book teaches you how to take full advantage of the framework by adding animations and special effects, implementing a physics engine, and optimizing your games.</p> <p>Prepare your project for multiple platforms and learn how to take your game concepts to completion.</p> <p>"Cocos2d-X by Example Beginner's Guide" will present to you, in six different games, the topics necessary to build some of the most popular and fun types of games today.</p>
Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – coding the GameLayer interface


GameLayer is the main container in our game and is coded as follows:

  1. Select your GameLayer.h, then replace the code here with:

    #ifndef __GAMELAYER_H__
    #define __GAMELAYER_H__
    
    #define GOAL_WIDTH 400

    We define the width of the goals in pixels.

  2. Next add the declarations for our sprites and our score text labels:

    #include "cocos2d.h"
    #include "GameSprite.h"
    
    using namespace cocos2d;
    
    class GameLayer : public cocos2d::CCLayer
    {
        GameSprite * _player1;
        GameSprite * _player2;
        GameSprite * _ball;
        
        CCArray * _players;
        CCLabelTTF * _player1ScoreLabel;
        CCLabelTTF * _player2ScoreLabel;

    We have the GameSprite objects for two players (the weird looking things called mallets), and the ball (called puck). We'll store the two players in CCArray. And we have two text labels to display score for each player.

  3. Declare a variable to store the screen size. We'll use this a lot for positioning:

    CCSize _screenSize;
  4. Add variables to store the score...