- Cocos2d-x by Example:Beginner's Guide(Second Edition)
- Roger Engelbert
- 253字
- 2021-07-23 20:00:28
Time for action – implementing GameSprite
With the header out of the way, all we need to do is implement our methods.
- 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; }
- Next we need to override the
Node
methodsetPosition
. 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; } }
- 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.
推薦閱讀
- Java程序設計(慕課版)
- Django+Vue.js商城項目實戰
- Visual FoxPro程序設計教程(第3版)
- Java Web基礎與實例教程
- YARN Essentials
- R的極客理想:工具篇
- Python數據分析從0到1
- 深入理解Elasticsearch(原書第3版)
- Access 2010數據庫應用技術(第2版)
- ElasticSearch Cookbook(Second Edition)
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- 深入解析Java編譯器:源碼剖析與實例詳解
- Python滲透測試編程技術:方法與實踐(第2版)
- Learning IBM Bluemix
- Python3從入門到實戰