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

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 of our sprite, which we determine to be half its texture's width:
    float GameSprite::radius() {
        return getTexture()->getContentSize().width * 0.5f;
    }

What just happened?

Things only begin happening in the static method. We create a new GameSprite class, then we call initWithFile on it. This is a GameSprite method inherited from its super class; it returns a Boolean value for whether that operation succeeded. The static method ends by returning an autorelease version of the GameSprite object.

The setPosition override makes sure _nextPosition receives the position information whenever the sprite is placed somewhere. And the helper radius method returns half of the sprite's texture width.

Have a go hero

Change the radius method to an inline method in the interface and remove it from the implementation file.

主站蜘蛛池模板: 萨嘎县| 宁远县| 太和县| 庆阳市| 通城县| 衡东县| 博白县| 泰顺县| 无锡市| 安吉县| 黄石市| 河源市| 香港| 淳安县| 秦皇岛市| 苏州市| 龙川县| 雷波县| 舒兰市| 宽甸| 珲春市| 陆丰市| 文登市| 泾源县| 西和县| 冀州市| 新绛县| 淮南市| 梁河县| 本溪市| 新郑市| 武隆县| 兴城市| 嵊州市| 司法| 登封市| 五峰| 张家口市| 连州市| 柘城县| 凤阳县|