Adding the Game sprites

Unlike in the previous backgrounds, the Game scene's background will be moving, providing a scrolling effect. Before you dive into the background code, an update function needs to be scheduled to be called in every frame using the following steps:

  1. Schedule the update function in the init() method using the following code:
    this->scheduleUpdate();
  2. Declare the update function in the GameScene.h file using the following code:
    void update(float dt);
  3. Implement the update function in the GameScene.cpp file using the following code:
    void GameScreen::update(float dt)
    {
    
    }

The update function is used to handle the game's logic and takes a float parameter called delta time, which is the time between frames. As all devices are not capable of running at 60 fps, this is factored in during gameplay to provide a smooth experience across a wide variety of devices.

The following are the steps to implement a scrolling background:

  1. Declare a sprite array for the background consisting of two items. As the background will be scrolling, two sprites will be used to provide the illusion of a consistent background. However, once a sprite has gone off the screen, it will reset back. The following code needs to be added within the header:
    cocos2d::Sprite *backgroundSpriteArray[2];
  2. Initialize the sprite array and set the position of the sprites; so, one is displayed on the screen initially, and the other one below the screen will be displayed as the background scrolls upwards. Then, add these to the scene as children; all this will be done within the init() method:
    for (int i = 0; i < 2; i ++)
    {
        backgroundSpriteArray[i] = Sprite::create("GameScreen/Game_Screen_Background.png");
        backgroundSpriteArray[i]->setPosition(Point((visibleSize.width / 2) + origin.x, (-1 * visibleSize.height * i) + (visibleSize.height / 2) + origin.y));
        this->addChild(backgroundSpriteArray[i], -2);
    }
  3. Next, move the sprites within the update() method by factoring in the delta time (0.75 is just the speed that can be changed, possibly by the user in a settings scene, which could be implemented as a side task, and it is multiplied by the screen height to keep a constant speed on different devices). You will also need to add a visibleSize variable, similar to what we did in the constructor:
    for (int i = 0; i < 2; i ++)
        {
          backgroundSpriteArray[i]->setPosition(Point(backgroundSpriteArray[i]->getPosition().x, backgroundSpriteArray[i]->getPosition().y + (0.75 * visibleSize.height * dt)));
        }
  4. Although the backgrounds scroll, they do not reset once they have gone above the screen. Add the following code above the previous code:
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point origin = Director::getInstance()->getVisibleOrigin();
    for (int i = 0; i < 2; i ++)
    {
        if (backgroundSpriteArray[i]->getPosition().y >= visibleSize.height + (visibleSize.height / 2) -1)
        {
          backgroundSpriteArray[i]->setPosition(Point((visibleSize.width / 2) + origin.x, (-1 * visibleSize.height) + (visibleSize.height / 2)));
        }
    }

The background is now scrolling and resets once it has gone off the screen.

Now, the scrolling asteroids will be implemented. The asteroids will spawn every 2.5 seconds randomly in the x axis just below the screen. Once an asteroid goes off the screen, it will be destroyed. Add the following code to implement scrolling asteroids:

  1. Declare the spawn asteroid method in GameScene.h (the scheduler requires a float parameter for delta time, but doesn't need it to be used):
    void spawnAsteroid(float dt);
  2. Declare the asteroids that will be stored as a vector of sprites as they can be dynamically added and removed:
    std::vector<cocos2d::Sprite *> asteroids;
  3. Implement the scheduler within the init() method inside the GameScene.cpp file (as the game will spawn asteroids every 1.0 second. 1.0 is specified as the interval time, but if it isn't specified, the method will be run for every frame):
    this->schedule(schedule_selector(GameScreen::spawnAsteroid), 1.0);
  4. Implement the spawnAsteroid(float dt) method:
    void GameScreen::spawnAsteroid(float dt)
    {
        Size visibleSize = Director::getInstance()->getVisibleSize();
        Point origin = Director::getInstance()->getVisibleOrigin();
    
        int asteroidIndex = (arc4random() % 3) + 1;
        __String* asteroidString = __String::createWithFormat("GameScreen/Asteroid_%i.png", asteroidIndex);
    
        Sprite *tempAsteroid = Sprite::create(asteroidString->getCString());
    
        int xRandomPosition = (arc4random() % (int)(visibleSize.width - (tempAsteroid->getContentSize().width / 2))) + (tempAsteroid->getContentSize().width / 2);
    
        tempAsteroid->setPosition(Point(xRandomPosition + origin.x, -tempAsteroid->getContentSize().height + origin.y));
        asteroids.push_back(tempAsteroid);
        this->addChild(asteroids[asteroids.size() - 1], -1);
    }
  5. Before implementing the code to check whether an asteroid has gone off the screen, let's go over what the spawnAsteroid(float dt) method does:
    • Firstly, the visible size and origin are declared and initialized
    • Then, asteroidIndex stores a random number that determines which asteroid will be spawned (as there are three different asteroids)
    • Next, the filename for the random asteroid is created using Cocos2d-x's built-in __String object, and using this, a temporary asteroid sprite is declared and initialized
    • The asteroid is then positioned below the screen and randomly along the x axis
    • Then, the asteroid is added to the asteroids' vector
    • The asteroid is added as a child to the scene
  6. Finally, add the following code to the update(float dt) method, which will move the asteroids at the same speed as the speed at which the background is moving. Then, it will check whether the asteroid has moved off the screen; if so, it will remove the asteroid from the scene and from the asteroid's vector:
    for (int i = 0; i < asteroids.size(); i++)
    {
        asteroids[i]->setPosition(Point(asteroids[i]->getPosition().x, asteroids[i]->getPosition().y + (0.75 * visibleSize.height * dt)));
    
        if (asteroids[i]->getPosition().y > visibleSize.height * 2)
        {
          this->removeChild(asteroids[i]);
          asteroids.erase(asteroids.begin() + i);
        }
    }

The final sprite to be added is the player's spaceship; use the following steps:

  1. Declare the player sprite in the GameScene.h file:
    cocos2d::Sprite *playerSprite;
  2. Initialize the player sprite within the init() method in the GameScene.cpp file:
    playerSprite = Sprite::create("GameScreen/Space_Pod.png");
  3. Position the player sprite below the pause button centered along the x axis:
    playerSprite->setPosition(Point(visibleSize.width / 2, pauseItem->getPosition().y - (pauseItem->getContentSize().height / 2) - (playerSprite->getContentSize().height / 2)));
  4. Now add the player sprite as a child to the scene:
    this->addChild(playerSprite, -1);

Now that the sprites have been implemented, here are the images of how the GameScene.h and GameScene.cpp files should look.

The following screenshot shows how the GameScene.h file should look after all the code has been added by following the previous steps:

Adding the Game sprites

The following screenshot shows how the init() method inside GameScene.cpp should look after all the code has been added by following the previous steps to initialize the game's sprites:

Adding the Game sprites

The following screenshot shows how the update() and spawnAsteroid() methods inside GameScene.cpp should look after all the code has been added by following the previous steps in order to add the asteroids randomly to provide a gameplay element to the game:

Adding the Game sprites

Note

In this tutorial, although speed was implemented as a magic number for general development purposes, this should be avoided and #defines or variables should be used.

Finally, this is how our GUI will look:

Adding the Game sprites
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset