首页 > 代码库 > cocod2d-x 之 CCDirector、CCScene、CCSprite
cocod2d-x 之 CCDirector、CCScene、CCSprite
CCDirector是控制游戏流程的主要组件。
1 typedef enum { 2 /// sets a 2D projection (orthogonal projection)2D投机模式 3 kCCDirectorProjection2D, 4 5 /// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500.3D投影 6 kCCDirectorProjection3D, 7 8 /// it calls "updateProjection" on the projection delegate. 9 kCCDirectorProjectionCustom, 10 11 /// Default projection is 3D projection 12 kCCDirectorProjectionDefault = kCCDirectorProjection3D, 13 } ccDirectorProjection; 14 15 class CC_DLL CCDirector : public CCObject, public TypeInfo 16 { 17 public: 18 19 CCDirector(void); 20 virtual ~CCDirector(void); 21 virtual bool init(void); 22 virtual long getClassTypeInfo() { 23 static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CCDirector).name()); 24 return id; 25 } 26 27 //获取当前运行的Scene 28 inline CCScene* getRunningScene(void) { return m_pRunningScene; } 29 30 /** Get the FPS value *///获取动画绘制间隔 31 inline double getAnimationInterval(void) { return m_dAnimationInterval; } 32 /** Set the FPS value. *///设置动画间隔 33 virtual void setAnimationInterval(double dValue) = 0; 34 35 /** Whether or not to display the FPS on the bottom-left corner *///是否显示状态fps、绘制间隔等 36 inline bool isDisplayStats(void) { return m_bDisplayStats; } 37 /** Display the FPS on the bottom-left corner */ 38 inline void setDisplayStats(bool bDisplayStats) { m_bDisplayStats = bDisplayStats; } 39 40 /** seconds per frame *///每秒钟绘制多少帧 41 inline float getSecondsPerFrame() { return m_fSecondsPerFrame; } 42 43 /** Get the CCEGLView, where everything is rendered 44 * @js NA 45 */ 46 inline CCEGLView* getOpenGLView(void) { return m_pobOpenGLView; } 47 void setOpenGLView(CCEGLView *pobOpenGLView); 48 49 inline bool isNextDeltaTimeZero(void) { return m_bNextDeltaTimeZero; } 50 void setNextDeltaTimeZero(bool bNextDeltaTimeZero); 51 52 /** Whether or not the Director is paused *///是否暂停 53 inline bool isPaused(void) { return m_bPaused; } 54 55 /** How many frames were called since the director started *///共绘制了多少帧 56 inline unsigned int getTotalFrames(void) { return m_uTotalFrames; } 57 58 /** Sets an OpenGL projection 59 @since v0.8.2 60 @js NA 61 */ 62 inline ccDirectorProjection getProjection(void) { return m_eProjection; } 63 void setProjection(ccDirectorProjection kProjection); 64 /** reshape projection matrix when canvas has been change"*/画布改变后,重塑投影矩阵 65 void reshapeProjection(const CCSize& newWindowSize); 66 67 /** Sets the glViewport*/ 68 void setViewport(); 69 70 /** How many frames were called since the director started */ 71 inline bool isSendCleanupToScene(void) { return m_bSendCleanupToScene; } 72 73 CCNode* getNotificationNode(); 74 void setNotificationNode(CCNode *node); 75 76 /** CCDirector delegate. It shall implemente the CCDirectorDelegate protocol 77 */ 78 CCDirectorDelegate* getDelegate() const; 79 void setDelegate(CCDirectorDelegate* pDelegate); 80 81 // window size,设计分辨率 82 /** returns the size of the OpenGL view in points. 83 */ 84 CCSize getWinSize(void); 85 86 /** returns the size of the OpenGL view in pixels. 87 */ 88 CCSize getWinSizeInPixels(void); 89 90 /** returns visible size of the OpenGL view in points. 91 * the value is equal to getWinSize if don‘t invoke 92 * CCEGLView::setDesignResolutionSize() 93 *///openGL的可视区大小,是在 WinSize 之内,保持 FrameSize 的宽高比所能占用的最大区域? 94 CCSize getVisibleSize(); 95 96 /** returns visible origin of the OpenGL view in points. 97 */ 98 CCPoint getVisibleOrigin(); 99 100 /** converts a UIKit coordinate to an OpenGL coordinate101 Useful to convert (multi) touch coordinates to the current layout (portrait or landscape)102 *///将一个点坐标从UI坐标(坐上角为原点)转换为openGL坐标(左下角为坐标),主要用于在点击事件中将点击坐标转换为屏幕坐标103 CCPoint convertToGL(const CCPoint& obPoint);104 105 /** converts an OpenGL coordinate to a UIKit coordinate106 Useful to convert node points to window points for calls such as glScissor107 *///将一个点转换为UI坐标的点108 CCPoint convertToUI(const CCPoint& obPoint);109 110 /// XXX: missing description 111 float getZEye(void);112 113 // Scene Management114 115 /** Enters the Director‘s main loop with the given Scene.116 * Call it to run only your FIRST scene.117 * Don‘t call it if there is already a running scene.118 *119 * It will call pushScene: and then it will call startAnimation120 *///加载场景并运行,游戏开始时调用121 void runWithScene(CCScene *pScene);122 123 /** Suspends the execution of the running scene, pushing it on the stack of suspended scenes.124 * The new scene will be executed.125 * Try to avoid big stacks of pushed scenes to reduce memory allocation. 126 * ONLY call it if there is a running scene.127 */128 void pushScene(CCScene *pScene);129 130 /** Pops out a scene from the queue.131 * This scene will replace the running one.132 * The running scene will be deleted. If there are no more scenes in the stack the execution is terminated.133 * ONLY call it if there is a running scene.134 */135 void popScene(void);136 137 /** Pops out all scenes from the queue until the root scene in the queue.138 * This scene will replace the running one.139 * Internally it will call `popToSceneStackLevel(1)`140 */141 void popToRootScene(void);142 143 /** Pops out all scenes from the queue until it reaches `level`.144 If level is 0, it will end the director.145 If level is 1, it will pop all scenes until it reaches to root scene.146 If level is <= than the current stack level, it won‘t do anything.147 */148 void popToSceneStackLevel(int level);149 150 /** Replaces the running scene with a new one. The running scene is terminated.151 * ONLY call it if there is a running scene.152 */153 void replaceScene(CCScene *pScene);154 155 /** Ends the execution, releases the running scene.156 It doesn‘t remove the OpenGL view from its parent. You have to do it manually.157 *///游戏结束,释放场景,但未移除openGL view158 void end(void);159 160 /** Pauses the running scene.161 The running scene will be _drawed_ but all scheduled timers will be paused162 While paused, the draw rate will be 4 FPS to reduce CPU consumption163 *///游戏暂停164 void pause(void);165 166 /** Resumes the paused scene167 The scheduled timers will be activated again.168 The "delta time" will be 0 (as if the game wasn‘t paused)169 *///游戏恢复170 void resume(void);171 172 /** Stops the animation. Nothing will be drawn. The main loop won‘t be triggered anymore.173 If you don‘t want to pause your animation call [pause] instead.174 *///停止动画175 virtual void stopAnimation(void) = 0;176 177 /** The main loop is triggered again.178 Call this function only if [stopAnimation] was called earlier179 @warning Don‘t call this function to start the main loop. To run the main loop call runWithScene180 *///开始动画181 virtual void startAnimation(void) = 0;182 183 /** Draw the scene.184 This method is called every frame. Don‘t call it manually.185 */186 void drawScene(void);187 188 // Memory Helper189 190 /** Removes cached all cocos2d cached data.191 It will purge the CCTextureCache, CCSpriteFrameCache, CCLabelBMFont cache192 @since v0.99.3193 *///清楚缓存数据,包括纹理、精灵、Label等194 void purgeCachedData(void);195 196 /** sets the default values based on the CCConfiguration info */197 void setDefaultValues(void);198 199 // OpenGL Helper200 201 /** sets the OpenGL default values */202 void setGLDefaultValues(void);203 204 /** enables/disables OpenGL alpha blending */205 void setAlphaBlending(bool bOn);206 207 /** enables/disables OpenGL depth test */208 void setDepthTest(bool bOn);209 210 virtual void mainLoop(void) = 0;211 212 /** The size in pixels of the surface. It could be different than the screen size.213 High-res devices might have a higher surface size than the screen size.214 Only available when compiled using SDK >= 4.0.215 @since v0.99.4216 *///设置缩放参数217 void setContentScaleFactor(float scaleFactor);218 float getContentScaleFactor(void);219 220 public:221 /** CCScheduler associated with this director222 @since v2.0223 *///声明成员属性224 CC_PROPERTY(CCScheduler*, m_pScheduler, Scheduler);225 226 /** CCActionManager associated with this director227 @since v2.0228 */229 CC_PROPERTY(CCActionManager*, m_pActionManager, ActionManager);230 231 /** CCTouchDispatcher associated with this director232 @since v2.0233 */234 CC_PROPERTY(CCTouchDispatcher*, m_pTouchDispatcher, TouchDispatcher);235 236 /** CCKeypadDispatcher associated with this director237 @since v2.0238 */239 CC_PROPERTY(CCKeypadDispatcher*, m_pKeypadDispatcher, KeypadDispatcher);240 241 /** CCAccelerometer associated with this director242 @since v2.0243 @js NA244 @lua NA245 */246 CC_PROPERTY(CCAccelerometer*, m_pAccelerometer, Accelerometer);247 248 /* delta time since last tick to main loop */249 CC_PROPERTY_READONLY(float, m_fDeltaTime, DeltaTime);250 251 public:252 /** returns a shared instance of the director 253 * @js getInstance254 */255 static CCDirector* sharedDirector(void);256 257 protected:258 259 void purgeDirector();//清空director260 bool m_bPurgeDirecotorInNextLoop; // this flag will be set to true in end()261 262 void setNextScene(void);263 264 void showStats();265 void createStatsLabel();266 void calculateMPF();267 void getFPSImageData(unsigned char** datapointer, unsigned int* length);268 269 /** calculates delta time since last time it was called */ 270 void calculateDeltaTime();271 protected:272 /* The CCEGLView, where everything is rendered */273 CCEGLView *m_pobOpenGLView;274 275 double m_dAnimationInterval;276 double m_dOldAnimationInterval;277 278 /* landscape mode ? */279 bool m_bLandscape;280 281 bool m_bDisplayStats;282 float m_fAccumDt;283 float m_fFrameRate;284 285 CCLabelAtlas *m_pFPSLabel;286 CCLabelAtlas *m_pSPFLabel;287 CCLabelAtlas *m_pDrawsLabel;288 289 /** Whether or not the Director is paused */290 bool m_bPaused;//是否暂停291 292 /* How many frames were called since the director started */293 /* 开始运行后共渲染了多少帧 */294 unsigned int m_uTotalFrames;295 unsigned int m_uFrames;296 float m_fSecondsPerFrame;//每秒的帧率297 298 /* The running scene */299 CCScene *m_pRunningScene;//当前场景300 301 /* will be the next ‘runningScene‘ in the next frame302 nextScene is a weak reference. */303 CCScene *m_pNextScene;//下一个场景304 305 /* If YES, then "old" scene will receive the cleanup message */306 bool m_bSendCleanupToScene;//是否清空前一个场景307 308 /* scheduled scenes */309 CCArray* m_pobScenesStack;//scene场景列表310 311 /* last time the main loop was updated */312 struct cc_timeval *m_pLastUpdate;//游戏主循环上一次刷新的时间313 314 /* whether or not the next delta time will be zero */315 bool m_bNextDeltaTimeZero;316 317 /* projection used */318 ccDirectorProjection m_eProjection;319 320 /* window size in points */321 CCSize m_obWinSizeInPoints;//窗口大小322 323 /* content scale factor */324 float m_fContentScaleFactor;//缩放325 326 /* store the fps string */327 char *m_pszFPS;328 329 /* This object will be visited after the scene. Useful to hook a notification node */330 CCNode *m_pNotificationNode;331 332 /* Projection protocol delegate */333 CCDirectorDelegate *m_pProjectionDelegate;//代理334 335 // CCEGLViewProtocol will recreate stats labels to fit visible rect//根据模式重绘画面,用于适配各种屏幕分辨率336 friend class CCEGLViewProtocol;337 };338 339 CCDirector.h
CCDirector常用方法
CCDirector *pDirector = CCDirector::sharedDirector() //获取CCDirector
runWithScene(CCScene* scene) //启动游戏并运行scene
replaceScene(CCScene* scene) //使用传入的scene替换当前场景来切换画面,当前场景将被释放
pushScene(CCScene* scene) //将当前运行中的场景暂停并压入到代执行场景栈中,再将传入的scene设置为当前运行场景
popScene() //释放当前场景,再从代执行场景栈中弹出栈顶的场景,并将其设置为当前运行场景。如果栈为空,则直接结束应用
pause() //暂停当前运行场景中的所有计时器和动作,场景仍然会显示在屏幕上
resume() //恢复当前运行场景中被暂停的计时器和动作。它与pause配合使用
end() //结束场景,同时退出应用
以上三种切换场景的方法(replaceScene、pushScene、popScene)均是先将待切换的场景完全加载完毕后,才将当前运行的场景释放掉。所以,在新场景恰好完全加载完毕的瞬间,系统中同时存在着两个场景,这将是对内存的一个考验,若不注意的话,切换场景可能会造成内存不足
CCScene定义了一个场景。场景只是层的容器,包含了所有需要显示的游戏元素
CCLayer定义了一个层。与CCScene类似,层也扮演着容器的角色。然而与场景不同的是,层通常包含的是直接呈现在屏幕上的具体内容.
1 //cocos2d-x-2.2/cocos2dx/layers_scenes_transitions_nodes/CCLayer.h 2 3 class CC_DLL CCLayer : public CCNode, public CCTouchDelegate, public CCAccelerometerDelegate, public CCKeypadDelegate 4 { 5 public: 6 CCLayer(); 7 virtual ~CCLayer(); 8 virtual bool init(); 9 static CCLayer *create(void);10 virtual void onEnter();11 virtual void onExit();12 virtual void onEnterTransitionDidFinish();13 14 // 触摸事件处理函数15 virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);16 virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);17 virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);18 virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);19 20 // 多点触摸21 virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);22 virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);23 virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);24 virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent);25 26 virtual void didAccelerate(CCAcceleration* pAccelerationValue);27 void registerScriptAccelerateHandler(int nHandler);28 void unregisterScriptAccelerateHandler(void);29 30 virtual void registerWithTouchDispatcher(void);31 32 /** Register script touch events handler */33 //注册触摸事件34 virtual void registerScriptTouchHandler(int nHandler, bool bIsMultiTouches = false, int nPriority = INT_MIN, bool bSwallowsTouches = false);35 /** Unregister script touch events handler */36 virtual void unregisterScriptTouchHandler(void);37 38 /** 是否处理触摸事件39 */40 virtual bool isTouchEnabled();41 virtual void setTouchEnabled(bool value);42 43 virtual void setTouchMode(ccTouchesMode mode);44 virtual int getTouchMode();45 46 /** priority of the touch events. Default is 0 */47 virtual void setTouchPriority(int priority);48 virtual int getTouchPriority();49 50 /** whether or not it will receive Accelerometer events51 You can enable / disable accelerometer events with this property.52 @since v0.8.153 */54 virtual bool isAccelerometerEnabled();55 virtual void setAccelerometerEnabled(bool value);56 virtual void setAccelerometerInterval(double interval);57 58 /** whether or not it will receive keypad events59 You can enable / disable accelerometer events with this property.60 it‘s new in cocos2d-x61 */62 virtual bool isKeypadEnabled();63 virtual void setKeypadEnabled(bool value);64 65 /** Register keypad events handler */66 void registerScriptKeypadHandler(int nHandler);67 /** Unregister keypad events handler */68 void unregisterScriptKeypadHandler(void);69 70 virtual void keyBackClicked(void);71 virtual void keyMenuClicked(void);72 73 inline CCTouchScriptHandlerEntry* getScriptTouchHandlerEntry() { return m_pScriptTouchHandlerEntry; };74 inline CCScriptHandlerEntry* getScriptKeypadHandlerEntry() { return m_pScriptKeypadHandlerEntry; };75 inline CCScriptHandlerEntry* getScriptAccelerateHandlerEntry() { return m_pScriptAccelerateHandlerEntry; };76 protected: 77 bool m_bTouchEnabled;78 bool m_bAccelerometerEnabled;79 bool m_bKeypadEnabled;80 81 private:82 // Script touch events handler83 CCTouchScriptHandlerEntry* m_pScriptTouchHandlerEntry;84 CCScriptHandlerEntry* m_pScriptKeypadHandlerEntry;85 CCScriptHandlerEntry* m_pScriptAccelerateHandlerEntry;86 87 int m_nTouchPriority;88 ccTouchesMode m_eTouchMode;89 90 int excuteScriptTouchHandler(int nEventType, CCTouch *pTouch);91 int excuteScriptTouchHandler(int nEventType, CCSet *pTouches);92 };
向场景中添加层,我们可以使用addChild方法。
void addChild(CCNode* child);
void addChild(CCNode* child, int zOrder);
void addChild(CCNode* child, int zOrder, int tag);
其中child参数为将要添加的节点。对于场景而言,通常我们添加的节点就是层。先添加的层会被置于后添加的层之下。如果想要为它们指定先后次序,可以使用不同的zOrder值,zOrder代表了该节点下元素的先后次序,值越大则显示顺序越靠上。zOrder的默认值为0。tag是元素的标识号码,如果为子节点设置了tag值,就可以在它的父节点中利用tag值找到它了。这里我们可以选择自己需要的方法来向场景中添加层。
CCSprite是CCNode的一个最重要也最灵活的子类。说它重要是因为CCSprite代表了游戏中一个最小的可见单位,说它灵活则是由于其装载了一个平面纹理,具有丰富的表现力,而且可以通过多种方式加载。如果说CCScene和CCLayer代表了宏观的游戏元素管理,那么CCSprite则为微观世界提供了丰富灵活的细节表现。
创建精灵
CCSprite* fish = CCSprite::create("fish.png");
这个工厂方法包含一个字符串参数,表示精灵所用纹理的文件名。CCSprite会自动把图片作为纹理载入到游戏中,然后使用纹理初始化精灵。
CCSprite* smallFish = CCSprite::create("fishes.png", CCRectMake(0, 0, 100, 100));
仅显示纹理的一部分。
向层中添加精灵
this->addChild(fish);
初始化方法
static CCSprite* create(const char *pszFileName);
static CCSprite* create(const char *pszFileName, const CCRect& rect);
bool initWithFile(const char *pszFilename);
bool initWithFile(const char *pszFilename, const CCRect& rect);
使用CCTexture2D纹理创建精灵
static CCSprite* create(CCTexture2D *pTexture);
static CCSprite* create(CCTexture2D *pTexture, const CCRect& rect);
bool initWithTexture(CCTexture2D *pTexture);
bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect);
使用CCSpriteFrame精灵框帧创建精灵
static CCSprite* create(CCSpriteFrame *pSpriteFrame);
bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame);
1 //cocos2d-x-2.2/cocos2dx/sprite_nodes/CCSprite.h 2 class CC_DLL CCSprite : public CCNodeRGBA, public CCTextureProtocol 3 #ifdef EMSCRIPTEN 4 , public CCGLBufferedNode 5 #endif // EMSCRIPTEN 6 { 7 public: 8 /// @{ 9 /// @name Creators 10 11 /** 12 * Creates an empty sprite without texture. You can call setTexture method subsequently. 13 * 14 * @return An empty sprite object that is marked as autoreleased. 15 */ 16 static CCSprite* create(); 17 18 /** 19 * Creates a sprite with an image filename. 20 * 21 * After creation, the rect of sprite will be the size of the image, 22 * and the offset will be (0,0). 23 * 24 * @param pszFileName The string which indicates a path to image file, e.g., "scene1/monster.png". 25 * @return A valid sprite object that is marked as autoreleased. 26 */ 27 static CCSprite* create(const char *pszFileName); 28 29 /** 30 * Creates a sprite with an image filename and a rect. 31 * 32 * @param pszFileName The string wich indicates a path to image file, e.g., "scene1/monster.png" 33 * @param rect Only the contents inside rect of pszFileName‘s texture will be applied for this sprite. 34 * @return A valid sprite object that is marked as autoreleased. 35 */ 36 static CCSprite* create(const char *pszFileName, const CCRect& rect); 37 38 /** 39 * Creates a sprite with an exsiting texture contained in a CCTexture2D object 40 * After creation, the rect will be the size of the texture, and the offset will be (0,0). 41 * 42 * @param pTexture A pointer to a CCTexture2D object. 43 * @return A valid sprite object that is marked as autoreleased. 44 */ 45 static CCSprite* createWithTexture(CCTexture2D *pTexture); 46 47 /** 48 * Creates a sprite with a texture and a rect. 49 * 50 * After creation, the offset will be (0,0). 51 * 52 * @param pTexture A pointer to an existing CCTexture2D object. 53 * You can use a CCTexture2D object for many sprites. 54 * @param rect Only the contents inside the rect of this texture will be applied for this sprite. 55 * @return A valid sprite object that is marked as autoreleased. 56 */ 57 static CCSprite* createWithTexture(CCTexture2D *pTexture, const CCRect& rect); 58 59 /** 60 * Creates a sprite with an sprite frame. 61 * 62 * @param pSpriteFrame A sprite frame which involves a texture and a rect 63 * @return A valid sprite object that is marked as autoreleased. 64 */ 65 static CCSprite* createWithSpriteFrame(CCSpriteFrame *pSpriteFrame); 66 67 /** 68 * Creates a sprite with an sprite frame name. 69 * 70 * A CCSpriteFrame will be fetched from the CCSpriteFrameCache by pszSpriteFrameName param. 71 * If the CCSpriteFrame doesn‘t exist it will raise an exception. 72 * 73 * @param pszSpriteFrameName A null terminated string which indicates the sprite frame name. 74 * @return A valid sprite object that is marked as autoreleased. 75 */ 76 static CCSprite* createWithSpriteFrameName(const char *pszSpriteFrameName); 77 78 /// @} end of creators group 79 80 81 82 /// @{ 83 /// @name Initializers 84 85 /** 86 * Default constructor 87 * @js ctor 88 */ 89 CCSprite(void); 90 91 /** 92 * Default destructor 93 * @js NA 94 * @lua NA 95 */ 96 virtual ~CCSprite(void); 97 98 /** 99 * Initializes an empty sprite with nothing init.100 */101 virtual bool init(void);102 103 /**104 * Initializes a sprite with a texture.105 *106 * After initialization, the rect used will be the size of the texture, and the offset will be (0,0).107 *108 * @param pTexture A pointer to an existing CCTexture2D object.109 * You can use a CCTexture2D object for many sprites.110 * @return true if the sprite is initialized properly, false otherwise.111 */112 virtual bool initWithTexture(CCTexture2D *pTexture);113 114 /**115 * Initializes a sprite with a texture and a rect.116 *117 * After initialization, the offset will be (0,0).118 *119 * @param pTexture A pointer to an exisiting CCTexture2D object.120 * You can use a CCTexture2D object for many sprites.121 * @param rect Only the contents inside rect of this texture will be applied for this sprite.122 * @return true if the sprite is initialized properly, false otherwise.123 */124 virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect);125 126 /**127 * Initializes a sprite with a texture and a rect in points, optionally rotated.128 *129 * After initialization, the offset will be (0,0).130 * @note This is the designated initializer.131 *132 * @param pTexture A CCTexture2D object whose texture will be applied to this sprite.133 * @param rect A rectangle assigned the contents of texture.134 * @param rotated Whether or not the texture rectangle is rotated.135 * @return true if the sprite is initialized properly, false otherwise.136 */137 virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect, bool rotated);138 139 /**140 * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite141 *142 * @param pSpriteFrame A CCSpriteFrame object. It should includes a valid texture and a rect143 * @return true if the sprite is initialized properly, false otherwise.144 */145 virtual bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame);146 147 /**148 * Initializes a sprite with an sprite frame name.149 *150 * A CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.151 * If the CCSpriteFrame doesn‘t exist it will raise an exception.152 *153 * @param pszSpriteFrameName A key string that can fected a volid CCSpriteFrame from CCSpriteFrameCache154 * @return true if the sprite is initialized properly, false otherwise.155 */156 virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName);157 158 /**159 * Initializes a sprite with an image filename.160 *161 * This method will find pszFilename from local file system, load its content to CCTexture2D,162 * then use CCTexture2D to create a sprite.163 * After initialization, the rect used will be the size of the image. The offset will be (0,0).164 *165 * @param pszFilename The path to an image file in local file system166 * @return true if the sprite is initialized properly, false otherwise.167 * @js init168 */169 virtual bool initWithFile(const char *pszFilename);170 171 /**172 * Initializes a sprite with an image filename, and a rect.173 *174 * This method will find pszFilename from local file system, load its content to CCTexture2D,175 * then use CCTexture2D to create a sprite.176 * After initialization, the offset will be (0,0).177 *178 * @param pszFilename The path to an image file in local file system.179 * @param rect The rectangle assigned the content area from texture.180 * @return true if the sprite is initialized properly, false otherwise.181 * @js init182 */183 virtual bool initWithFile(const char *pszFilename, const CCRect& rect);184 185 /// @} end of initializers186 187 /// @{188 /// @name Functions inherited from CCTextureProtocol189 virtual void setTexture(CCTexture2D *texture);190 virtual CCTexture2D* getTexture(void);191 inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = blendFunc; }192 /**193 * @js NA194 */195 inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; }196 /// @}197 198 /// @{199 /// @name Functions inherited from CCNode200 virtual void setScaleX(float fScaleX);201 virtual void setScaleY(float fScaleY);202 /**203 * @lua NA204 */205 virtual void setPosition(const CCPoint& pos);206 virtual void setRotation(float fRotation);207 virtual void setRotationX(float fRotationX);208 virtual void setRotationY(float fRotationY);209 virtual void setSkewX(float sx);210 virtual void setSkewY(float sy);211 virtual void removeChild(CCNode* pChild, bool bCleanup);212 virtual void removeAllChildrenWithCleanup(bool bCleanup);213 virtual void reorderChild(CCNode *pChild, int zOrder);214 virtual void addChild(CCNode *pChild);215 virtual void addChild(CCNode *pChild, int zOrder);216 virtual void addChild(CCNode *pChild, int zOrder, int tag);217 virtual void sortAllChildren();218 virtual void setScale(float fScale);219 virtual void setVertexZ(float fVertexZ);220 virtual void setAnchorPoint(const CCPoint& anchor);221 virtual void ignoreAnchorPointForPosition(bool value);222 virtual void setVisible(bool bVisible);223 virtual void draw(void);224 /// @}225 226 /// @{227 /// @name Functions inherited from CCNodeRGBA228 virtual void setColor(const ccColor3B& color3);229 virtual void updateDisplayedColor(const ccColor3B& parentColor);230 virtual void setOpacity(GLubyte opacity);231 virtual void setOpacityModifyRGB(bool modify);232 virtual bool isOpacityModifyRGB(void);233 virtual void updateDisplayedOpacity(GLubyte parentOpacity);234 /// @}235 236 237 /// @{238 /// @name BatchNode methods239 240 /**241 * Updates the quad according the rotation, position, scale values. 242 */243 virtual void updateTransform(void);244 245 /**246 * Returns the batch node object if this sprite is rendered by CCSpriteBatchNode247 *248 * @return The CCSpriteBatchNode object if this sprite is rendered by CCSpriteBatchNode,249 * NULL if the sprite isn‘t used batch node.250 */251 virtual CCSpriteBatchNode* getBatchNode(void);252 /**253 * Sets the batch node to sprite254 * @warning This method is not recommended for game developers. Sample code for using batch node255 * @code256 * CCSpriteBatchNode *batch = CCSpriteBatchNode::create("Images/grossini_dance_atlas.png", 15);257 * CCSprite *sprite = CCSprite::createWithTexture(batch->getTexture(), CCRectMake(0, 0, 57, 57));258 * batch->addChild(sprite);259 * layer->addChild(batch);260 * @endcode261 */262 virtual void setBatchNode(CCSpriteBatchNode *pobSpriteBatchNode);263 264 /// @} end of BatchNode methods265 266 267 268 /// @{269 /// @name Texture methods270 271 /**272 * Updates the texture rect of the CCSprite in points.273 * It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size.274 */275 virtual void setTextureRect(const CCRect& rect);276 277 /**278 * Sets the texture rect, rectRotated and untrimmed size of the CCSprite in points.279 * It will update the texture coordinates and the vertex rectangle.280 */281 virtual void setTextureRect(const CCRect& rect, bool rotated, const CCSize& untrimmedSize);282 283 /**284 * Sets the vertex rect.285 * It will be called internally by setTextureRect.286 * Useful if you want to create 2x images from SD images in Retina Display.287 * Do not call it manually. Use setTextureRect instead.288 */289 virtual void setVertexRect(const CCRect& rect);290 291 /// @} end of texture methods292 293 294 295 /// @{296 /// @name Frames methods297 298 /**299 * Sets a new display frame to the CCSprite.300 */301 virtual void setDisplayFrame(CCSpriteFrame *pNewFrame);302 303 /**304 * Returns whether or not a CCSpriteFrame is being displayed305 */306 virtual bool isFrameDisplayed(CCSpriteFrame *pFrame);307 308 /**309 * Returns the current displayed frame.310 * @js NA311 */312 virtual CCSpriteFrame* displayFrame(void);313 314 /// @} End of frames methods315 316 317 /// @{318 /// @name Animation methods319 /**320 * Changes the display frame with animation name and index.321 * The animation name will be get from the CCAnimationCache322 */323 virtual void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex);324 /// @}325 326 327 /// @{328 /// @name Sprite Properties‘ setter/getters329 330 /** 331 * Whether or not the Sprite needs to be updated in the Atlas.332 *333 * @return true if the sprite needs to be updated in the Atlas, false otherwise.334 */335 inline virtual bool isDirty(void) { return m_bDirty; }336 337 /** 338 * Makes the Sprite to be updated in the Atlas.339 */340 inline virtual void setDirty(bool bDirty) { m_bDirty = bDirty; }341 342 /**343 * Returns the quad (tex coords, vertex coords and color) information.344 * @js NA345 */346 inline ccV3F_C4B_T2F_Quad getQuad(void) { return m_sQuad; }347 348 /** 349 * Returns whether or not the texture rectangle is rotated.350 */351 inline bool isTextureRectRotated(void) { return m_bRectRotated; }352 353 /** 354 * Returns the index used on the TextureAtlas. 355 */356 inline unsigned int getAtlasIndex(void) { return m_uAtlasIndex; }357 358 /** 359 * Sets the index used on the TextureAtlas.360 * @warning Don‘t modify this value unless you know what you are doing361 */362 inline void setAtlasIndex(unsigned int uAtlasIndex) { m_uAtlasIndex = uAtlasIndex; }363 364 /** 365 * Returns the rect of the CCSprite in points 366 */367 inline const CCRect& getTextureRect(void) { return m_obRect; }368 369 /**370 * Gets the weak reference of the CCTextureAtlas when the sprite is rendered using via CCSpriteBatchNode371 */372 inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas; }373 374 /**375 * Sets the weak reference of the CCTextureAtlas when the sprite is rendered using via CCSpriteBatchNode376 */377 inline void setTextureAtlas(CCTextureAtlas *pobTextureAtlas) { m_pobTextureAtlas = pobTextureAtlas; }378 379 /** 380 * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex.381 */382 inline const CCPoint& getOffsetPosition(void) { return m_obOffsetPosition; }383 384 385 /** 386 * Returns the flag which indicates whether the sprite is flipped horizontally or not.387 *388 * It only flips the texture of the sprite, and not the texture of the sprite‘s children.389 * Also, flipping the texture doesn‘t alter the anchorPoint.390 * If you want to flip the anchorPoint too, and/or to flip the children too use:391 * sprite->setScaleX(sprite->getScaleX() * -1);392 *393 * @return true if the sprite is flipped horizaontally, false otherwise.394 * @js isFlippedX395 */396 bool isFlipX(void);397 /**398 * Sets whether the sprite should be flipped horizontally or not.399 *400 * @param bFlipX true if the sprite should be flipped horizaontally, false otherwise.401 */402 void setFlipX(bool bFlipX);403 404 /** 405 * Return the flag which indicates whether the sprite is flipped vertically or not.406 * 407 * It only flips the texture of the sprite, and not the texture of the sprite‘s children.408 * Also, flipping the texture doesn‘t alter the anchorPoint.409 * If you want to flip the anchorPoint too, and/or to flip the children too use:410 * sprite->setScaleY(sprite->getScaleY() * -1);411 * 412 * @return true if the sprite is flipped vertically, flase otherwise.413 * @js isFlippedY414 */415 bool isFlipY(void);416 /**417 * Sets whether the sprite should be flipped vertically or not.418 *419 * @param bFlipY true if the sprite should be flipped vertically, flase otherwise.420 */421 void setFlipY(bool bFlipY);422 423 /// @} End of Sprite properties getter/setters424 425 protected:426 void updateColor(void);427 virtual void setTextureCoords(CCRect rect);428 virtual void updateBlendFunc(void);429 virtual void setReorderChildDirtyRecursively(void);430 virtual void setDirtyRecursively(bool bValue);431 432 //433 // Data used when the sprite is rendered using a CCSpriteSheet434 //435 CCTextureAtlas* m_pobTextureAtlas; /// CCSpriteBatchNode texture atlas (weak reference)436 unsigned int m_uAtlasIndex; /// Absolute (real) Index on the SpriteSheet437 CCSpriteBatchNode* m_pobBatchNode; /// Used batch node (weak reference)438 439 bool m_bDirty; /// Whether the sprite needs to be updated440 bool m_bRecursiveDirty; /// Whether all of the sprite‘s children needs to be updated441 bool m_bHasChildren; /// Whether the sprite contains children442 bool m_bShouldBeHidden; /// should not be drawn because one of the ancestors is not visible443 CCAffineTransform m_transformToBatch;444 445 //446 // Data used when the sprite is self-rendered447 //448 ccBlendFunc m_sBlendFunc; /// It‘s required for CCTextureProtocol inheritance449 CCTexture2D* m_pobTexture; /// CCTexture2D object that is used to render the sprite450 451 //452 // Shared data453 //454 455 // texture456 CCRect m_obRect; /// Retangle of CCTexture2D457 bool m_bRectRotated; /// Whether the texture is rotated458 459 // Offset Position (used by Zwoptex)460 CCPoint m_obOffsetPosition;461 CCPoint m_obUnflippedOffsetPositionFromCenter;462 463 // vertex coords, texture coords and color info464 ccV3F_C4B_T2F_Quad m_sQuad;465 466 // opacity and RGB protocol467 bool m_bOpacityModifyRGB;468 469 // image is flipped470 bool m_bFlipX; /// Whether the sprite is flipped horizaontally or not.471 bool m_bFlipY; /// Whether the sprite is flipped vertically or not.472 };473 474 CCSprite.h
CCNode与坐标系
Cocos2d-x采用了场景、层、精灵的层次结构来组织游戏元素,与此同时,这个层次结构还对应了游戏的渲染层次,因此游戏元素可以组织成树形结构,称作渲染树。Cocos2d-x把渲染树上的每一个游戏元素抽象为一个节点,即CCNode。一切游戏元素都继承自CCNode,因此它们都具有CCNode所提供的特性。
1 //cocos2d-x-2.2/cocos2dx/base_nodes/CCNode.h 2 3 enum { 4 kCCNodeTagInvalid = -1, 5 }; 6 7 enum { 8 kCCNodeOnEnter, 9 kCCNodeOnExit, 10 kCCNodeOnEnterTransitionDidFinish, 11 kCCNodeOnExitTransitionDidStart, 12 kCCNodeOnCleanup 13 }; 14 15 16 class CC_DLL CCNode : public CCObject 17 { 18 public: 19 /// @{ 20 /// @name Constructor, Distructor and Initializers 21 22 /** 23 * Default constructor 24 * @js ctor 25 */ 26 CCNode(void); 27 28 /** 29 * Default destructor 30 * @js NA 31 * @lua NA 32 */ 33 virtual ~CCNode(void); 34 35 /** 36 * Initializes the instance of CCNode 37 * @return Whether the initialization was successful. 38 */ 39 virtual bool init(); 40 /** 41 * Allocates and initializes a node. 42 * @return A initialized node which is marked as "autorelease". 43 */ 44 static CCNode * create(void); 45 46 /** 47 * Gets the description string. It makes debugging easier. 48 * @return A string terminated with ‘\0‘ 49 * @js NA 50 */ 51 const char* description(void); 52 53 /// @} end of initializers 54 55 56 57 /// @{ 58 /// @name Setters & Getters for Graphic Peroperties 59 60 /** 61 * Sets the Z order which stands for the drawing order, and reorder this node in its parent‘s children array. 62 * 63 * The Z order of node is relative to its "brothers": children of the same parent. 64 * It‘s nothing to do with OpenGL‘s z vertex. This one only affects the draw order of nodes in cocos2d. 65 * The larger number it is, the later this node will be drawn in each message loop. 66 * Please refer to setVertexZ(float) for the difference. 67 * 68 * @param nZOrder Z order of this node. 69 */ 70 virtual void setZOrder(int zOrder); 71 /** 72 * Sets the z order which stands for the drawing order 73 * 74 * This is an internal method. Don‘t call it outside the framework. 75 * The difference between setZOrder(int) and _setOrder(int) is: 76 * - _setZOrder(int) is a pure setter for m_nZOrder memeber variable 77 * - setZOrder(int) firstly changes m_nZOrder, then recorder this node in its parent‘s chilren array. 78 */ 79 virtual void _setZOrder(int z); 80 /** 81 * Gets the Z order of this node. 82 * 83 * @see setZOrder(int) 84 * 85 * @return The Z order. 86 */ 87 virtual int getZOrder(); 88 89 90 /** 91 * Sets the real OpenGL Z vertex. 92 * 93 * Differences between openGL Z vertex and cocos2d Z order: 94 * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children 95 * - OpenGL Z might require to set 2D projection 96 * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0 97 * 98 * @warning Use it at your own risk since it might break the cocos2d parent-children z order 99 * 100 * @param fVertexZ OpenGL Z vertex of this node. 101 */ 102 virtual void setVertexZ(float vertexZ); 103 /** 104 * Gets OpenGL Z vertex of this node. 105 * 106 * @see setVertexZ(float) 107 * 108 * @return OpenGL Z vertex of this node 109 */ 110 virtual float getVertexZ(); 111 112 113 /** 114 * Changes the scale factor on X axis of this node 115 * 116 * The deafult value is 1.0 if you haven‘t changed it before 117 * 118 * @param fScaleX The scale factor on X axis. 119 */ 120 virtual void setScaleX(float fScaleX); 121 /** 122 * Returns the scale factor on X axis of this node 123 * 124 * @see setScaleX(float) 125 * 126 * @return The scale factor on X axis. 127 */ 128 virtual float getScaleX(); 129 130 131 /** 132 * Changes the scale factor on Y axis of this node 133 * 134 * The Default value is 1.0 if you haven‘t changed it before. 135 * 136 * @param fScaleY The scale factor on Y axis. 137 */ 138 virtual void setScaleY(float fScaleY); 139 /** 140 * Returns the scale factor on Y axis of this node 141 * 142 * @see setScaleY(float) 143 * 144 * @return The scale factor on Y axis. 145 */ 146 virtual float getScaleY(); 147 148 149 /** 150 * Changes both X and Y scale factor of the node. 151 * 152 * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. 153 * 154 * @param scale The scale factor for both X and Y axis. 155 */ 156 virtual void setScale(float scale); 157 /** 158 * Gets the scale factor of the node, when X and Y have the same scale factor. 159 * 160 * @warning Assert when m_fScaleX != m_fScaleY. 161 * @see setScale(float) 162 * 163 * @return The scale factor of the node. 164 */ 165 virtual float getScale(); 166 167 168 /** 169 * Changes both X and Y scale factor of the node. 170 * 171 * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. 172 * 173 * @param fScaleX The scale factor on X axis. 174 * @param fScaleY The scale factor on Y axis. 175 */ 176 virtual void setScale(float fScaleX,float fScaleY); 177 178 179 /** 180 * Changes the position (x,y) of the node in OpenGL coordinates 181 * 182 * Usually we use ccp(x,y) to compose CCPoint object. 183 * The original point (0,0) is at the left-bottom corner of screen. 184 * For example, this codesnip sets the node in the center of screen. 185 * @code 186 * CCSize size = CCDirector::sharedDirector()->getWinSize(); 187 * node->setPosition( ccp(size.width/2, size.height/2) ) 188 * @endcode 189 * 190 * @param position The position (x,y) of the node in OpenGL coordinates 191 * @js NA 192 */ 193 virtual void setPosition(const CCPoint &position); 194 /** 195 * Gets the position (x,y) of the node in OpenGL coordinates 196 * 197 * @see setPosition(const CCPoint&) 198 * 199 * @return The position (x,y) of the node in OpenGL coordinates 200 */ 201 virtual const CCPoint& getPosition(); 202 /** 203 * Sets position in a more efficient way. 204 * 205 * Passing two numbers (x,y) is much efficient than passing CCPoint object. 206 * This method is binded to lua and javascript. 207 * Passing a number is 10 times faster than passing a object from lua to c++ 208 * 209 * @code 210 * // sample code in lua 211 * local pos = node::getPosition() -- returns CCPoint object from C++ 212 * node:setPosition(x, y) -- pass x, y coordinate to C++ 213 * @endcode 214 * 215 * @param x X coordinate for position 216 * @param y Y coordinate for position 217 * @js NA 218 */ 219 virtual void setPosition(float x, float y); 220 /** 221 * Gets position in a more efficient way, returns two number instead of a CCPoint object 222 * 223 * @see setPosition(float, float) 224 */ 225 virtual void getPosition(float* x, float* y); 226 /** 227 * Gets/Sets x or y coordinate individually for position. 228 * These methods are used in Lua and Javascript Bindings 229 */ 230 virtual void setPositionX(float x); 231 virtual float getPositionX(void); 232 virtual void setPositionY(float y); 233 virtual float getPositionY(void); 234 235 236 /** 237 * Changes the X skew angle of the node in degrees. 238 * 239 * This angle describes the shear distortion in the X direction. 240 * Thus, it is the angle between the Y axis and the left edge of the shape 241 * The default skewX angle is 0. Positive values distort the node in a CW direction. 242 * 243 * @param fSkewX The X skew angle of the node in degrees. 244 */ 245 virtual void setSkewX(float fSkewX); 246 /** 247 * Returns the X skew angle of the node in degrees. 248 * 249 * @see setSkewX(float) 250 * 251 * @return The X skew angle of the node in degrees. 252 */ 253 virtual float getSkewX(); 254 255 256 /** 257 * Changes the Y skew angle of the node in degrees. 258 * 259 * This angle describes the shear distortion in the Y direction. 260 * Thus, it is the angle between the X axis and the bottom edge of the shape 261 * The default skewY angle is 0. Positive values distort the node in a CCW direction. 262 * 263 * @param fSkewY The Y skew angle of the node in degrees. 264 */ 265 virtual void setSkewY(float fSkewY); 266 /** 267 * Returns the Y skew angle of the node in degrees. 268 * 269 * @see setSkewY(float) 270 * 271 * @return The Y skew angle of the node in degrees. 272 */ 273 virtual float getSkewY(); 274 275 276 /** 277 * Sets the anchor point in percent. 278 * 279 * anchorPoint is the point around which all transformations and positioning manipulations take place. 280 * It‘s like a pin in the node where it is "attached" to its parent. 281 * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. 282 * But you can use values higher than (1,1) and lower than (0,0) too. 283 * The default anchorPoint is (0.5,0.5), so it starts in the center of the node. 284 * 285 * @param anchorPoint The anchor point of node. 286 */ 287 virtual void setAnchorPoint(const CCPoint& anchorPoint); 288 /** 289 * Returns the anchor point in percent. 290 * 291 * @see setAnchorPoint(const CCPoint&) 292 * 293 * @return The anchor point of node. 294 */ 295 virtual const CCPoint& getAnchorPoint(); 296 /** 297 * Returns the anchorPoint in absolute pixels. 298 * 299 * @warning You can only read it. If you wish to modify it, use anchorPoint instead. 300 * @see getAnchorPoint() 301 * 302 * @return The anchor point in absolute pixels. 303 */ 304 virtual const CCPoint& getAnchorPointInPoints(); 305 306 307 /** 308 * Sets the untransformed size of the node. 309 * 310 * The contentSize remains the same no matter the node is scaled or rotated. 311 * All nodes has a size. Layer and Scene has the same size of the screen. 312 * 313 * @param contentSize The untransformed size of the node. 314 */ 315 virtual void setContentSize(const CCSize& contentSize); 316 /** 317 * Returns the untransformed size of the node. 318 * 319 * @see setContentSize(const CCSize&) 320 * 321 * @return The untransformed size of the node. 322 */ 323 virtual const CCSize& getContentSize() const; 324 325 326 /** 327 * Sets whether the node is visible 328 * 329 * The default value is true, a node is default to visible 330 * 331 * @param visible true if the node is visible, false if the node is hidden. 332 */ 333 virtual void setVisible(bool visible); 334 /** 335 * Determines if the node is visible 336 * 337 * @see setVisible(bool) 338 * 339 * @return true if the node is visible, false if the node is hidden. 340 */ 341 virtual bool isVisible(); 342 343 344 /** 345 * Sets the rotation (angle) of the node in degrees. 346 * 347 * 0 is the default rotation angle. 348 * Positive values rotate node clockwise, and negative values for anti-clockwise. 349 * 350 * @param fRotation The roration of the node in degrees. 351 */ 352 virtual void setRotation(float fRotation); 353 /** 354 * Returns the rotation of the node in degrees. 355 * 356 * @see setRotation(float) 357 * 358 * @return The rotation of the node in degrees. 359 */ 360 virtual float getRotation(); 361 362 363 /** 364 * Sets the X rotation (angle) of the node in degrees which performs a horizontal rotational skew. 365 * 366 * 0 is the default rotation angle. 367 * Positive values rotate node clockwise, and negative values for anti-clockwise. 368 * 369 * @param fRotationX The X rotation in degrees which performs a horizontal rotational skew. 370 */ 371 virtual void setRotationX(float fRotaionX); 372 /** 373 * Gets the X rotation (angle) of the node in degrees which performs a horizontal rotation skew. 374 * 375 * @see setRotationX(float) 376 * 377 * @return The X rotation in degrees. 378 */ 379 virtual float getRotationX(); 380 381 382 /** 383 * Sets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew. 384 * 385 * 0 is the default rotation angle. 386 * Positive values rotate node clockwise, and negative values for anti-clockwise. 387 * 388 * @param fRotationY The Y rotation in degrees. 389 */ 390 virtual void setRotationY(float fRotationY); 391 /** 392 * Gets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew. 393 * 394 * @see setRotationY(float) 395 * 396 * @return The Y rotation in degrees. 397 */ 398 virtual float getRotationY(); 399 400 401 /** 402 * Sets the arrival order when this node has a same ZOrder with other children. 403 * 404 * A node which called addChild subsequently will take a larger arrival order, 405 * If two children have the same Z order, the child with larger arrival order will be drawn later. 406 * 407 * @warning This method is used internally for zOrder sorting, don‘t change this manually 408 * 409 * @param uOrderOfArrival The arrival order. 410 */ 411 virtual void setOrderOfArrival(unsigned int uOrderOfArrival); 412 /** 413 * Returns the arrival order, indecates which children is added previously. 414 * 415 * @see setOrderOfArrival(unsigned int) 416 * 417 * @return The arrival order. 418 */ 419 virtual unsigned int getOrderOfArrival(); 420 421 422 /** 423 * Sets the state of OpenGL server side. 424 * 425 * @param glServerState The state of OpenGL server side. 426 * @js NA 427 */ 428 virtual void setGLServerState(ccGLServerState glServerState); 429 /** 430 * Returns the state of OpenGL server side. 431 * 432 * @return The state of OpenGL server side. 433 * @js NA 434 */ 435 virtual ccGLServerState getGLServerState(); 436 437 438 /** 439 * Sets whether the anchor point will be (0,0) when you position this node. 440 * 441 * This is an internal method, only used by CCLayer and CCScene. Don‘t call it outside framework. 442 * The default value is false, while in CCLayer and CCScene are true 443 * 444 * @param ignore true if anchor point will be (0,0) when you position this node 445 * @todo This method shoud be renamed as setIgnoreAnchorPointForPosition(bool) or something with "set" 446 */ 447 virtual void ignoreAnchorPointForPosition(bool ignore); 448 /** 449 * Gets whether the anchor point will be (0,0) when you position this node. 450 * 451 * @see ignoreAnchorPointForPosition(bool) 452 * 453 * @return true if the anchor point will be (0,0) when you position this node. 454 */ 455 virtual bool isIgnoreAnchorPointForPosition(); 456 457 /// @} end of Setters & Getters for Graphic Peroperties 458 459 460 /// @{ 461 /// @name Children and Parent 462 463 /** 464 * Adds a child to the container with z-order as 0. 465 * 466 * If the child is added to a ‘running‘ node, then ‘onEnter‘ and ‘onEnterTransitionDidFinish‘ will be called immediately. 467 * 468 * @param child A child node 469 */ 470 virtual void addChild(CCNode * child); 471 /** 472 * Adds a child to the container with a z-order 473 * 474 * If the child is added to a ‘running‘ node, then ‘onEnter‘ and ‘onEnterTransitionDidFinish‘ will be called immediately. 475 * 476 * @param child A child node 477 * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) 478 */ 479 virtual void addChild(CCNode * child, int zOrder); 480 /** 481 * Adds a child to the container with z order and tag 482 * 483 * If the child is added to a ‘running‘ node, then ‘onEnter‘ and ‘onEnterTransitionDidFinish‘ will be called immediately. 484 * 485 * @param child A child node 486 * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) 487 * @param tag A interger to identify the node easily. Please refer to setTag(int) 488 */ 489 virtual void addChild(CCNode* child, int zOrder, int tag); 490 /** 491 * Gets a child from the container with its tag 492 * 493 * @param tag An identifier to find the child node. 494 * 495 * @return a CCNode object whose tag equals to the input parameter 496 */ 497 CCNode * getChildByTag(int tag); 498 /** 499 * Return an array of children 500 * 501 * Composing a "tree" structure is a very important feature of CCNode 502 * Here‘s a sample code of traversing children array: 503 * @code 504 * CCNode* node = NULL; 505 * CCARRAY_FOREACH(parent->getChildren(), node) 506 * { 507 * node->setPosition(0,0); 508 * } 509 * @endcode 510 * This sample code traverses all children nodes, and set theie position to (0,0) 511 * 512 * @return An array of children 513 */ 514 virtual CCArray* getChildren(); 515 516 /** 517 * Get the amount of children. 518 * 519 * @return The amount of children. 520 */ 521 unsigned int getChildrenCount(void) const; 522 523 /** 524 * Sets the parent node 525 * 526 * @param parent A pointer to the parnet node 527 */ 528 virtual void setParent(CCNode* parent); 529 /** 530 * Returns a pointer to the parent node 531 * 532 * @see setParent(CCNode*) 533 * 534 * @returns A pointer to the parnet node 535 */ 536 virtual CCNode* getParent(); 537 538 539 ////// REMOVES ////// 540 541 /** 542 * Removes this node itself from its parent node with a cleanup. 543 * If the node orphan, then nothing happens. 544 * @see removeFromParentAndCleanup(bool) 545 */ 546 virtual void removeFromParent(); 547 /** 548 * Removes this node itself from its parent node. 549 * If the node orphan, then nothing happens. 550 * @param cleanup true if all actions and callbacks on this node should be removed, false otherwise. 551 * @js removeFromParent 552 */ 553 virtual void removeFromParentAndCleanup(bool cleanup); 554 /** 555 * Removes a child from the container with a cleanup 556 * 557 * @see removeChild(CCNode, bool) 558 * 559 * @param child The child node which will be removed. 560 */ 561 virtual void removeChild(CCNode* child); 562 /** 563 * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. 564 * 565 * @param child The child node which will be removed. 566 * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. 567 */ 568 virtual void removeChild(CCNode* child, bool cleanup); 569 /** 570 * Removes a child from the container by tag value with a cleanup. 571 * 572 * @see removeChildByTag(int, bool) 573 * 574 * @param tag An interger number that identifies a child node 575 */ 576 virtual void removeChildByTag(int tag); 577 /** 578 * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter 579 * 580 * @param tag An interger number that identifies a child node 581 * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. 582 */ 583 virtual void removeChildByTag(int tag, bool cleanup); 584 /** 585 * Removes all children from the container with a cleanup. 586 * 587 * @see removeAllChildrenWithCleanup(bool) 588 */ 589 virtual void removeAllChildren(); 590 /** 591 * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. 592 * 593 * @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise. 594 * @js removeAllChildren 595 */ 596 virtual void removeAllChildrenWithCleanup(bool cleanup); 597 598 /** 599 * Reorders a child according to a new z value. 600 * 601 * @param child An already added child node. It MUST be already added. 602 * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) 603 */ 604 virtual void reorderChild(CCNode * child, int zOrder); 605 606 /** 607 * Sorts the children array once before drawing, instead of every time when a child is added or reordered. 608 * This appraoch can improves the performance massively. 609 * @note Don‘t call this manually unless a child added needs to be removed in the same frame 610 */ 611 virtual void sortAllChildren(); 612 613 /// @} end of Children and Parent 614 615 616 617 /// @{ 618 /// @name Grid object for effects 619 620 /** 621 * Returns a grid object that is used when applying effects 622 * 623 * @return A CCGrid object that is used when applying effects 624 * @js NA 625 */ 626 virtual CCGridBase* getGrid(); 627 /** 628 * Changes a grid object that is used when applying effects 629 * 630 * @param A CCGrid object that is used when applying effects 631 */ 632 virtual void setGrid(CCGridBase *pGrid); 633 634 /// @} end of Grid 635 636 637 /// @{ 638 /// @name Tag & User data 639 640 /** 641 * Returns a tag that is used to identify the node easily. 642 * 643 * You can set tags to node then identify them easily. 644 * @code 645 * #define TAG_PLAYER 1 646 * #define TAG_MONSTER 2 647 * #define TAG_BOSS 3 648 * // set tags 649 * node1->setTag(TAG_PLAYER); 650 * node2->setTag(TAG_MONSTER); 651 * node3->setTag(TAG_BOSS); 652 * parent->addChild(node1); 653 * parent->addChild(node2); 654 * parent->addChild(node3); 655 * // identify by tags 656 * CCNode* node = NULL; 657 * CCARRAY_FOREACH(parent->getChildren(), node) 658 * { 659 * switch(node->getTag()) 660 * { 661 * case TAG_PLAYER: 662 * break; 663 * case TAG_MONSTER: 664 * break; 665 * case TAG_BOSS: 666 * break; 667 * } 668 * } 669 * @endcode 670 * 671 * @return A interger that identifies the node. 672 */ 673 virtual int getTag() const; 674 /** 675 * Changes the tag that is used to identify the node easily. 676 * 677 * Please refer to getTag for the sample code. 678 * 679 * @param A interger that indentifies the node. 680 */ 681 virtual void setTag(int nTag); 682 683 /** 684 * Returns a custom user data pointer 685 * 686 * You can set everything in UserData pointer, a data block, a structure or an object. 687 * 688 * @return A custom user data pointer 689 * @js NA 690 */ 691 virtual void* getUserData(); 692 /** 693 * Sets a custom user data pointer 694 * 695 * You can set everything in UserData pointer, a data block, a structure or an object, etc. 696 * @warning Don‘t forget to release the memroy manually, 697 * especially before you change this data pointer, and before this node is autoreleased. 698 * 699 * @return A custom user data pointer 700 * @js NA 701 */ 702 virtual void setUserData(void *pUserData); 703 704 /** 705 * Returns a user assigned CCObject 706 * 707 * Similar to userData, but instead of holding a void* it holds an object 708 * 709 * @return A user assigned CCObject 710 * @js NA 711 */ 712 virtual CCObject* getUserObject(); 713 /** 714 * Returns a user assigned CCObject 715 * 716 * Similar to UserData, but instead of holding a void* it holds an object. 717 * The UserObject will be retained once in this method, 718 * and the previous UserObject (if existed) will be relese. 719 * The UserObject will be released in CCNode‘s destructure. 720 * 721 * @param A user assigned CCObject 722 */ 723 virtual void setUserObject(CCObject *pUserObject); 724 725 /// @} end of Tag & User Data 726 727 728 /// @{ 729 /// @name Shader Program 730 /** 731 * Return the shader program currently used for this node 732 * 733 * @return The shader program currelty used for this node 734 */ 735 virtual CCGLProgram* getShaderProgram(); 736 /** 737 * Sets the shader program for this node 738 * 739 * Since v2.0, each rendering node must set its shader program. 740 * It should be set in initialize phase. 741 * @code 742 * node->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor)); 743 * @endcode 744 * 745 * @param The shader program which fetchs from CCShaderCache. 746 */ 747 virtual void setShaderProgram(CCGLProgram *pShaderProgram); 748 /// @} end of Shader Program 749 750 751 /** 752 * Returns a camera object that lets you move the node using a gluLookAt 753 * 754 * @code 755 * CCCamera* camera = node->getCamera(); 756 * camera->setEyeXYZ(0, 0, 415/2); 757 * camera->setCenterXYZ(0, 0, 0); 758 * @endcode 759 * 760 * @return A CCCamera object that lets you move the node using a gluLookAt 761 */ 762 virtual CCCamera* getCamera(); 763 764 /** 765 * Returns whether or not the node accepts event callbacks. 766 * 767 * Running means the node accept event callbacks like onEnter(), onExit(), update() 768 * 769 * @return Whether or not the node is running. 770 */ 771 virtual bool isRunning(); 772 773 774 /// @{ 775 /// @name Script Bindings for lua 776 777 /** 778 * Registers a script function that will be called in onEnter() & onExit() seires functions. 779 * 780 * This handler will be removed automatically after onExit() called. 781 * @code 782 * -- lua sample 783 * local function sceneEventHandler(eventType) 784 * if eventType == kCCNodeOnEnter then 785 * -- do something 786 * elseif evetType == kCCNodeOnExit then 787 * -- do something 788 * end 789 * end 790 * scene::registerScriptHandler(sceneEventHandler) 791 * @endcode 792 * 793 * @warning This method is for internal usage, don‘t call it manually. 794 * @todo Perhaps we should rename it to get/set/removeScriptHandler acoording to the function name style. 795 * 796 * @param handler A number that indicates a lua function. 797 */ 798 virtual void registerScriptHandler(int handler); 799 /** 800 * Unregisters a script function that will be called in onEnter() & onExit() series functions. 801 * 802 * @see registerScriptHandler(int) 803 */ 804 virtual void unregisterScriptHandler(void); 805 /** 806 * Gets script handler for onEnter/onExit event. 807 * This is an internal method. g 808 * @see registerScriptHandler(int) 809 * 810 * @return A number that indicates a lua function. 811 */ 812 inline int getScriptHandler() { return m_nScriptHandler; }; 813 814 /** 815 * Schedules for lua script. 816 * @js NA 817 */ 818 void scheduleUpdateWithPriorityLua(int nHandler, int priority); 819 820 /// @} end Script Bindings 821 822 823 /// @{ 824 /// @name Event Callbacks 825 826 /** 827 * Event callback that is invoked every time when CCNode enters the ‘stage‘. 828 * If the CCNode enters the ‘stage‘ with a transition, this event is called when the transition starts. 829 * During onEnter you can‘t access a "sister/brother" node. 830 * If you override onEnter, you shall call its parent‘s one, e.g., CCNode::onEnter(). 831 * @js NA 832 * @lua NA 833 */ 834 virtual void onEnter(); 835 836 /** Event callback that is invoked when the CCNode enters in the ‘stage‘. 837 * If the CCNode enters the ‘stage‘ with a transition, this event is called when the transition finishes. 838 * If you override onEnterTransitionDidFinish, you shall call its parent‘s one, e.g. CCNode::onEnterTransitionDidFinish() 839 * @js NA 840 * @lua NA 841 */ 842 virtual void onEnterTransitionDidFinish(); 843 844 /** 845 * Event callback that is invoked every time the CCNode leaves the ‘stage‘. 846 * If the CCNode leaves the ‘stage‘ with a transition, this event is called when the transition finishes. 847 * During onExit you can‘t access a sibling node. 848 * If you override onExit, you shall call its parent‘s one, e.g., CCNode::onExit(). 849 * @js NA 850 * @lua NA 851 */ 852 virtual void onExit(); 853 854 /** 855 * Event callback that is called every time the CCNode leaves the ‘stage‘. 856 * If the CCNode leaves the ‘stage‘ with a transition, this callback is called when the transition starts. 857 * @js NA 858 * @lua NA 859 */ 860 virtual void onExitTransitionDidStart(); 861 862 /// @} end of event callbacks. 863 864 865 /** 866 * Stops all running actions and schedulers 867 */ 868 virtual void cleanup(void); 869 870 /** 871 * Override this method to draw your own node. 872 * The following GL states will be enabled by default: 873 * - glEnableClientState(GL_VERTEX_ARRAY); 874 * - glEnableClientState(GL_COLOR_ARRAY); 875 * - glEnableClientState(GL_TEXTURE_COORD_ARRAY); 876 * - glEnable(GL_TEXTURE_2D); 877 * AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE 878 * But if you enable any other GL state, you should disable it after drawing your node. 879 */ 880 virtual void draw(void); 881 882 /** 883 * Visits this node‘s children and draw them recursively. 884 */ 885 virtual void visit(void); 886 887 888 /** 889 * Returns a "local" axis aligned bounding box of the node. 890 * The returned box is relative only to its parent. 891 * 892 * @note This method returns a temporaty variable, so it can‘t returns const CCRect& 893 * @todo Rename to getBoundingBox() in the future versions. 894 * 895 * @return A "local" axis aligned boudning box of the node. 896 * @js getBoundingBox 897 */ 898 CCRect boundingBox(void); 899 900 /// @{ 901 /// @name Actions 902 903 /** 904 * Sets the CCActionManager object that is used by all actions. 905 * 906 * @warning If you set a new CCActionManager, then previously created actions will be removed. 907 * 908 * @param actionManager A CCActionManager object that is used by all actions. 909 */ 910 virtual void setActionManager(CCActionManager* actionManager); 911 /** 912 * Gets the CCActionManager object that is used by all actions. 913 * @see setActionManager(CCActionManager*) 914 * @return A CCActionManager object. 915 */ 916 virtual CCActionManager* getActionManager(); 917 918 /** 919 * Executes an action, and returns the action that is executed. 920 * 921 * This node becomes the action‘s target. Refer to CCAction::getTarget() 922 * @warning Actions don‘t retain their target. 923 * 924 * @return An Action pointer 925 */ 926 CCAction* runAction(CCAction* action); 927 928 /** 929 * Stops and removes all actions from the running action list . 930 */ 931 void stopAllActions(void); 932 933 /** 934 * Stops and removes an action from the running action list. 935 * 936 * @param An action object to be removed. 937 */ 938 void stopAction(CCAction* action); 939 940 /** 941 * Removes an action from the running action list by its tag. 942 * 943 * @param A tag that indicates the action to be removed. 944 */ 945 void stopActionByTag(int tag); 946 947 /** 948 * Gets an action from the running action list by its tag. 949 * 950 * @see setTag(int), getTag(). 951 * 952 * @return The action object with the given tag. 953 */ 954 CCAction* getActionByTag(int tag); 955 956 /** 957 * Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays). 958 * 959 * Composable actions are counted as 1 action. Example: 960 * If you are running 1 Sequence of 7 actions, it will return 1. 961 * If you are running 7 Sequences of 2 actions, it will return 7. 962 * @todo Rename to getNumberOfRunningActions() 963 * 964 * @return The number of actions that are running plus the ones that are schedule to run 965 */ 966 unsigned int numberOfRunningActions(void); 967 968 /// @} end of Actions 969 970 971 /// @{ 972 /// @name Scheduler and Timer 973 974 /** 975 * Sets a CCScheduler object that is used to schedule all "updates" and timers. 976 * 977 * @warning If you set a new CCScheduler, then previously created timers/update are going to be removed. 978 * @param scheduler A CCShdeduler object that is used to schedule all "update" and timers. 979 * @js NA 980 */ 981 virtual void setScheduler(CCScheduler* scheduler); 982 /** 983 * Gets a CCSheduler object. 984 * 985 * @see setScheduler(CCScheduler*) 986 * @return A CCScheduler object. 987 * @js NA 988 */ 989 virtual CCScheduler* getScheduler(); 990 991 /** 992 * Checks whether a selector is scheduled. 993 * 994 * @param selector A function selector 995 * @return Whether the funcion selector is scheduled. 996 * @js NA 997 * @lua NA 998 */ 999 bool isScheduled(SEL_SCHEDULE selector);1000 1001 /** 1002 * Schedules the "update" method. 1003 *1004 * It will use the order number 0. This method will be called every frame.1005 * Scheduled methods with a lower order value will be called before the ones that have a higher order value.1006 * Only one "update" method could be scheduled per node.1007 * @lua NA1008 */1009 void scheduleUpdate(void);1010 1011 /** 1012 * Schedules the "update" method with a custom priority. 1013 *1014 * This selector will be called every frame.1015 * Scheduled methods with a lower priority will be called before the ones that have a higher value.1016 * Only one "update" selector could be scheduled per node (You can‘t have 2 ‘update‘ selectors).1017 * @lua NA1018 */1019 void scheduleUpdateWithPriority(int priority);1020 1021 /* 1022 * Unschedules the "update" method.1023 * @see scheduleUpdate();1024 */1025 void unscheduleUpdate(void);1026 1027 /**1028 * Schedules a custom selector.1029 *1030 * If the selector is already scheduled, then the interval parameter will be updated without scheduling it again.1031 * @code1032 * // firstly, implement a schedule function1033 * void MyNode::TickMe(float dt);1034 * // wrap this function into a selector via schedule_selector marco.1035 * this->schedule(schedule_selector(MyNode::TickMe), 0, 0, 0);1036 * @endcode1037 *1038 * @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it‘s recommended to use scheduleUpdate() instead.1039 * @param repeat The selector will be excuted (repeat + 1) times, you can use kCCRepeatForever for tick infinitely.1040 * @param delay The amount of time that the first tick will wait before execution.1041 * @lua NA1042 */1043 void schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay);1044 1045 /**1046 * Schedules a custom selector with an interval time in seconds.1047 * @see schedule(SEL_SCHEDULE, float, unsigned int, float)1048 *1049 * @param selector A function wrapped as a selector1050 * @param interval Callback interval time in seconds. 0 means tick every frame,1051 * @lua NA1052 */1053 void schedule(SEL_SCHEDULE selector, float interval);1054 1055 /**1056 * Schedules a selector that runs only once, with a delay of 0 or larger1057 * @see schedule(SEL_SCHEDULE, float, unsigned int, float)1058 *1059 * @param selector A function wrapped as a selector1060 * @param delay The amount of time that the first tick will wait before execution.1061 * @lua NA1062 */1063 void scheduleOnce(SEL_SCHEDULE selector, float delay);1064 1065 /**1066 * Schedules a custom selector, the scheduled selector will be ticked every frame1067 * @see schedule(SEL_SCHEDULE, float, unsigned int, float)1068 *1069 * @param selector A function wrapped as a selector1070 * @lua NA1071 */1072 void schedule(SEL_SCHEDULE selector);1073 1074 /** 1075 * Unschedules a custom selector.1076 * @see schedule(SEL_SCHEDULE, float, unsigned int, float)1077 *1078 * @param selector A function wrapped as a selector1079 * @lua NA1080 */1081 void unschedule(SEL_SCHEDULE selector);1082 1083 /** 1084 * Unschedule all scheduled selectors: custom selectors, and the ‘update‘ selector.1085 * Actions are not affected by this method.1086 */1087 void unscheduleAllSelectors(void);1088 1089 /** 1090 * Resumes all scheduled selectors and actions.1091 * This method is called internally by onEnter1092 * @js NA1093 * @lua NA1094 */1095 void resumeSchedulerAndActions(void);1096 /** 1097 * Pauses all scheduled selectors and actions.1098 * This method is called internally by onExit1099 * @js NA1100 * @lua NA1101 */1102 void pauseSchedulerAndActions(void);1103 1104 /* 1105 * Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live"1106 */1107 virtual void update(float delta);1108 1109 /// @} end of Scheduler and Timer1110 1111 /// @{1112 /// @name Transformations1113 1114 /**1115 * Performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes.1116 */1117 void transform(void);1118 /**1119 * Performs OpenGL view-matrix transformation of it‘s ancestors.1120 * Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO)1121 * It‘s necessary to transform the ancestors again.1122 */1123 void transformAncestors(void);1124 /**1125 * Calls children‘s updateTransform() method recursively.1126 *1127 * This method is moved from CCSprite, so it‘s no longer specific to CCSprite.1128 * As the result, you apply CCSpriteBatchNode‘s optimization on your customed CCNode.1129 * e.g., batchNode->addChild(myCustomNode), while you can only addChild(sprite) before.1130 */1131 virtual void updateTransform(void);1132 1133 /** 1134 * Returns the matrix that transform the node‘s (local) space coordinates into the parent‘s space coordinates.1135 * The matrix is in Pixels.1136 */1137 virtual CCAffineTransform nodeToParentTransform(void);1138 1139 /** 1140 * Returns the matrix that transform parent‘s space coordinates to the node‘s (local) space coordinates.1141 * The matrix is in Pixels.1142 */1143 virtual CCAffineTransform parentToNodeTransform(void);1144 1145 /** 1146 * Returns the world affine transform matrix. The matrix is in Pixels.1147 */1148 virtual CCAffineTransform nodeToWorldTransform(void);1149 1150 /** 1151 * Returns the inverse world affine transform matrix. The matrix is in Pixels.1152 */1153 virtual CCAffineTransform worldToNodeTransform(void);1154 1155 /// @} end of Transformations1156 1157 1158 /// @{1159 /// @name Coordinate Converters1160 1161 /** 1162 * Converts a Point to node (local) space coordinates. The result is in Points.1163 */1164 CCPoint convertToNodeSpace(const CCPoint& worldPoint);1165 1166 /** 1167 * Converts a Point to world space coordinates. The result is in Points.1168 */1169 CCPoint convertToWorldSpace(const CCPoint& nodePoint);1170 1171 /** 1172 * Converts a Point to node (local) space coordinates. The result is in Points.1173 * treating the returned/received node point as anchor relative.1174 */1175 CCPoint convertToNodeSpaceAR(const CCPoint& worldPoint);1176 1177 /** 1178 * Converts a local Point to world space coordinates.The result is in Points.1179 * treating the returned/received node point as anchor relative.1180 */1181 CCPoint convertToWorldSpaceAR(const CCPoint& nodePoint);1182 1183 /** 1184 * convenience methods which take a CCTouch instead of CCPoint1185 */1186 CCPoint convertTouchToNodeSpace(CCTouch * touch);1187 1188 /** 1189 * converts a CCTouch (world coordinates) into a local coordinate. This method is AR (Anchor Relative).1190 */1191 CCPoint convertTouchToNodeSpaceAR(CCTouch * touch);1192 1193 /**1194 * Sets the additional transform.1195 *1196 * @note The additional transform will be concatenated at the end of nodeToParentTransform.1197 * It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn‘t).1198 * @code1199 // create a batchNode1200 CCSpriteBatchNode* batch= CCSpriteBatchNode::create("Icon-114.png");1201 this->addChild(batch);1202 1203 // create two sprites, spriteA will be added to batchNode, they are using different textures.1204 CCSprite* spriteA = CCSprite::createWithTexture(batch->getTexture());1205 CCSprite* spriteB = CCSprite::create("Icon-72.png");1206 1207 batch->addChild(spriteA); 1208 1209 // We can‘t make spriteB as spriteA‘s child since they use different textures. So just add it to layer.1210 // But we want to simulate `parent-child` relationship for these two node.1211 this->addChild(spriteB); 1212 1213 //position1214 spriteA->setPosition(ccp(200, 200));1215 1216 // Gets the spriteA‘s transform.1217 CCAffineTransform t = spriteA->nodeToParentTransform();1218 1219 // Sets the additional transform to spriteB, spriteB‘s postion will based on its pseudo parent i.e. spriteA.1220 spriteB->setAdditionalTransform(t);1221 1222 //scale1223 spriteA->setScale(2);1224 1225 // Gets the spriteA‘s transform.1226 t = spriteA->nodeToParentTransform();1227 1228 // Sets the additional transform to spriteB, spriteB‘s scale will based on its pseudo parent i.e. spriteA.1229 spriteB->setAdditionalTransform(t);1230 1231 //rotation1232 spriteA->setRotation(20);1233 1234 // Gets the spriteA‘s transform.1235 t = spriteA->nodeToParentTransform();1236 1237 // Sets the additional transform to spriteB, spriteB‘s rotation will based on its pseudo parent i.e. spriteA.1238 spriteB->setAdditionalTransform(t);1239 * @endcode1240 */1241 void setAdditionalTransform(const CCAffineTransform& additionalTransform);1242 1243 /// @} end of Coordinate Converters1244 1245 /// @{1246 /// @name component functions1247 /** 1248 * gets a component by its name1249 */1250 CCComponent* getComponent(const char *pName) const;1251 1252 /** 1253 * adds a component1254 */1255 virtual bool addComponent(CCComponent *pComponent);1256 1257 /** 1258 * removes a component by its name 1259 */1260 virtual bool removeComponent(const char *pName);1261 1262 /**1263 * removes all components1264 */1265 virtual void removeAllComponents();1266 /// @} end of component functions1267 1268 private:1269 /// lazy allocs1270 void childrenAlloc(void);1271 1272 /// helper that reorder a child1273 void insertChild(CCNode* child, int z);1274 1275 /// Removes a child, call child->onExit(), do cleanup, remove it from children array.1276 void detachChild(CCNode *child, bool doCleanup);1277 1278 /** Convert cocos2d coordinates to UI windows coordinate.1279 * @js NA1280 * @lua NA1281 */1282 CCPoint convertToWindowSpace(const CCPoint& nodePoint);1283 1284 protected:1285 float m_fRotationX; ///< rotation angle on x-axis1286 float m_fRotationY; ///< rotation angle on y-axis1287 1288 float m_fScaleX; ///< scaling factor on x-axis1289 float m_fScaleY; ///< scaling factor on y-axis1290 1291 float m_fVertexZ; ///< OpenGL real Z vertex1292 1293 CCPoint m_obPosition; ///< position of the node1294 1295 float m_fSkewX; ///< skew angle on x-axis1296 float m_fSkewY; ///< skew angle on y-axis1297 1298 CCPoint m_obAnchorPointInPoints; ///< anchor point in points1299 CCPoint m_obAnchorPoint; ///< anchor point normalized (NOT in points)1300 1301 CCSize m_obContentSize; ///< untransformed size of the node1302 1303 1304 CCAffineTransform m_sAdditionalTransform; ///< transform1305 CCAffineTransform m_sTransform; ///< transform1306 CCAffineTransform m_sInverse; ///< transform1307 1308 CCCamera *m_pCamera; ///< a camera1309 1310 CCGridBase *m_pGrid; ///< a grid1311 1312 int m_nZOrder; ///< z-order value that affects the draw order1313 1314 CCArray *m_pChildren; ///< array of children nodes1315 CCNode *m_pParent; ///< weak reference to parent node1316 1317 int m_nTag; ///< a tag. Can be any number you assigned just to identify this node1318 1319 void *m_pUserData; ///< A user assingned void pointer, Can be point to any cpp object1320 CCObject *m_pUserObject; ///< A user assigned CCObject1321 1322 CCGLProgram *m_pShaderProgram; ///< OpenGL shader1323 1324 ccGLServerState m_eGLServerState; ///< OpenGL servier side state1325 1326 unsigned int m_uOrderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder1327 1328 CCScheduler *m_pScheduler; ///< scheduler used to schedule timers and updates1329 1330 CCActionManager *m_pActionManager; ///< a pointer to ActionManager singleton, which is used to handle all the actions1331 1332 bool m_bRunning; ///< is running1333 1334 bool m_bTransformDirty; ///< transform dirty flag1335 bool m_bInverseDirty; ///< transform dirty flag1336 bool m_bAdditionalTransformDirty; ///< The flag to check whether the additional transform is dirty1337 bool m_bVisible; ///< is this node visible1338 1339 bool m_bIgnoreAnchorPointForPosition; ///< true if the Anchor Point will be (0,0) when you position the CCNode, false otherwise.1340 ///< Used by CCLayer and CCScene.1341 1342 bool m_bReorderChildDirty; ///< children order dirty flag1343 1344 int m_nScriptHandler; ///< script handler for onEnter() & onExit(), used in Javascript binding and Lua binding.1345 int m_nUpdateScriptHandler; ///< script handler for update() callback per frame, which is invoked from lua & javascript.1346 ccScriptType m_eScriptType; ///< type of script binding, lua or javascript1347 1348 CCComponentContainer *m_pComponentContainer; ///< Dictionary of components1349 1350 };1351 1352 CCNode.h
在Cocos2d-x中,存在两种坐标系。
绘图坐标系。它是最常见的坐标系,与OpenGL采用的坐标系相同,以左下角为原点,向右为x轴正方向,向上为y轴正方向。在Cocos2d-x中,一切绘图相关的操作都使用绘图坐标系,如游戏元素中的Position和AnchorPoint等属性。
纹理坐标系。纹理坐标系以左上角为原点,向右为x轴正方向,向下为y轴正方向,如图3-2所示。在Cocos2d-x中,只有从纹理中截取部分矩形时才使用这个坐标系,如CCSprite的TextureRect属性。
CCRect ContentSize:获取或设置此节点的内容大小。任何一个节点都需要确定它的内容大小,以便进行图形变换。对于精灵来说,ContentSize是它的纹理显示部分的大小;对于层或场景等全屏的大型节点来说,ContentSize则是屏幕大小。
CCPoint AnchorPoint与CCPoint Position:AnchorPoint用于设置一个锚点,以便精确地控制节点的位置和变换。AnchorPoint的两个参量x和y的取值通常都是0到1之间的实数,表示锚点相对于节点长宽的位置。例如,把节点左下角作为锚点,值为(0,0);把节点的中心作为锚点,值为(0.5,0.5);把节点右下角作为锚点,值为(1,0)。精灵的AnchorPoint默认值为(0.5,0.5),其他节点的默认值为(0,0)。
Position用于设置节点的位置。由于Position指的是锚点在父节点中的坐标值,节点显示的位置通常与锚点有关。因此,如果层与场景保持默认的位置,只需把层中精灵位置设为窗口长宽的一半即可让它显示在屏幕中央。
对于场景或层等大型节点,它们的IgnoreAnchorPointForPosition属性为true,此时引擎会认为AnchorPoint永远为(0,0);而其他节点的该属性为flase,它们的锚点不会被忽略。
int Tag:获取或设置节点的标号。在Cocos2d-x中,Tag的作用类似于标识符,以便快速地从节点的所有子节点中找出所需节点。Tag可以用于定位子节点,因此添加到同一节点的所有CCNode之中,不能有两个节点的Tag相同,否则就给定位带来了麻烦。与Tag相关的方法有getChildByTag、removeChildByTag等。
定时器事件
定时器是以一定时间间隔连续引发游戏事件的工具。。Cocos2d-x为我们提供了两种方式实现定时机制--使用update方法以及使用schedule方法。
第一种定时机制是CCNode的刷新事件update方法,该方法在每帧绘制之前都会被触发一次。由于绘图帧率有限,而每次更新最终会反映到画面上,所以在每帧之间刷新一次已经足够应付大部分游戏逻辑处理的要求了。CCNode默认并没有启用update事件,为了启用定时器,我们需要调用scheduleUpdate方法,并重载update以执行自己的代码。对应地,我们可以使用unscheduleUpdate方法停止定时器。
另一种定时机制是CCNode提供的schedule方法,可以实现以一定的时间间隔连续调用某个函数。由于引擎的调度机制,这里的时间间隔必须大于两帧的间隔,否则两帧期间的多次调用会被合并成一次调用。
由于Cocos2d-x的调度是纯粹的串行机制,因此所有函数都运行在同一个线程,不会存在并行程序的种种麻烦。
CCNode中与定时器相关的方法
方法 | 描述 |
isScheduled(SEL_SCHEDULE selector) | 返回一个值,表示selector对应的函数是否已被添加为定时器 |
scheduleUpdate | 启用update定时器 |
scheduleUpdateWithPriority(int priority) | 启用update定时器,并设定定时器的优先级 |
unscheduleUpdate | 取消update定时器 |
schedule(SEL_SCHEDULE selector, float delay) | 添加一个schedule定时器,其中selector |
scheduleOnce(SEL_SCHEDULE selector, float delay) | 添加一个schedule定时器,但定时器只触发一次 |
unschedule(SEL_SCHEDULE selector) | 取消selector所对应函数的定时器 |
unscheduleAllSelectors | 取消此节点所关联的全部定时器 |
pauseSchedulerAndActions | 暂停此节点所关联的全部定时器与动作 |
resumeSchedulerAndActions | 继续执行此节点所关联的定时器与动作 |
onEnter() | 当此节点所在场景即将呈现时,会调用此方法 |
onEnterTransitionDidFinish() | 当此节点所在场景的入场动作结束后,会调用此方法。如果所在场景没有入场动作,则此方法会紧接着onEnter()后被调用 |
onExit() | 当此节点所在场景即将退出时,会调用此方法 |
onExitTransitionDidStart() | 当此节点所在场景的出场动作结束后,会调用此方法。如果所在场景没有出场动作,则此方法会紧接着onExit()后被调用 |
Cocos2d-x内置的常用层
为了方便游戏开发者,Cocos2d-x内置了3种特殊的CCLayer。CCLayerColor:一个单纯的实心色块。CCLayerGradient:一个色块,但可以设置两种颜色的渐变效果。CCMenu:十分常用的游戏菜单。
CCLayerColor拥有以下初始化方法:如果采用指定了宽与高的初始化方法,则创建一个指定大小的色块;如果采用不指定大小的初始化方法,则创建一个屏幕大小的色块。CCLayerColor的创建方法和初始化方法如下所示:
static CCLayerColor * create(const ccColor4B& color);
static CCLayerColor * create(const ccColor4B& color, GLfloat width, GLfloat height);
bool initWithColor(const ccColor4B& color);
bool initWithColor(const ccColor4B& color, GLfloat width, GLfloat height);
CCLayerGradient与CCLayerColor类似,但是它在初始化时需要指定两种颜色以及渐变的方向。在初始化方法中,start参数为起始颜色,end参数为结束颜色,而v是方向向量。CCLayerGradient的创建方法和初始化方法如下所示:
static CCLayerGradient* create(const ccColor4B& start, const ccColor4B& end);
static CCLayerGradient* create(const ccColor4B& start, const ccColor4B& end, const CCPoint& v);
bool initWithColor(const ccColor4B& start, const ccColor4B& end);
bool initWithColor(const ccColor4B& start, const ccColor4B& end, const CCPoint& v);
在色块创建后,也可以通过下面列举的方法来修改色块大小:
void changeWidth(GLfloat w);
void changeHeight(GLfloat h);
void changeWidthAndHeight(GLfloat w ,GLfloat h);
CCMenu:游戏菜单
菜单是游戏不可或缺的一部分。在Cocos2d-x中,菜单由两部分组成,分别是菜单项和菜单本身。CCMenuItem表示一个菜单项,每个菜单项都是一个独立的按钮,定义了菜单的视觉表现和响应动作;CCMenu则是菜单,它负责将菜单项组织到一起并添加到场景中,转换屏幕的触摸事件到各个菜单项。
CCMenuItemImage::create(
"CloseNormal.png", //普通状态下的图片
"CloseSelected.png", //按下状态下的图片
this, //响应对象
menu_selector(HelloWorld::menuCloseCallback)); //响应函数
其中响应函数必须满足SEL_MenuHandler形式:返回值为空,带一个CCNode*型的参数。