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

Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – implementing GameSprite


With the header out of the way, all we need to do is implement our methods.

  1. Select the GameSprite.cpp file and let's start on the instantiation logic of the class:

    #include "GameSprite.h"
    
    GameSprite::GameSprite(void){
        _vector = Vec2(0,0);
    }
    
    GameSprite::~GameSprite(void){
    }
    
    GameSprite* GameSprite::gameSpriteWithFile(const char * pszFileName) {
       auto sprite = new GameSprite();
       if (sprite && sprite->initWithFile(pszFileName)) {
              sprite->autorelease();
              return sprite;
       }
       CC_SAFE_DELETE(sprite);
       return sprite = nullptr;
    }
  2. Next we need to override the Node method setPosition. We need to make sure that whenever we change the position of the sprite, the new value is also used by _nextPosition:

    void GameSprite::setPosition(const Point& pos) {
        Sprite::setPosition(pos);
        if (!_nextPosition.equals(pos)) {
            _nextPosition = pos;
        }
    }
  3. And finally, we implement our new method to retrieve the radius...