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 coordinate 101 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 coordinate 106 Useful to convert node points to window points for calls such as glScissor 107 *///将一个点转换为UI坐标的点 108 CCPoint convertToUI(const CCPoint& obPoint); 109 110 /// XXX: missing description 111 float getZEye(void); 112 113 // Scene Management 114 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 startAnimation 120 *///加载场景并运行,游戏开始时调用 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 view 158 void end(void); 159 160 /** Pauses the running scene. 161 The running scene will be _drawed_ but all scheduled timers will be paused 162 While paused, the draw rate will be 4 FPS to reduce CPU consumption 163 *///游戏暂停 164 void pause(void); 165 166 /** Resumes the paused scene 167 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 earlier 179 @warning Don't call this function to start the main loop. To run the main loop call runWithScene 180 *///开始动画 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 Helper 189 190 /** Removes cached all cocos2d cached data. 191 It will purge the CCTextureCache, CCSpriteFrameCache, CCLabelBMFont cache 192 @since v0.99.3 193 *///清楚缓存数据,包括纹理、精灵、Label等 194 void purgeCachedData(void); 195 196 /** sets the default values based on the CCConfiguration info */ 197 void setDefaultValues(void); 198 199 // OpenGL Helper 200 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.4 216 *///设置缩放参数 217 void setContentScaleFactor(float scaleFactor); 218 float getContentScaleFactor(void); 219 220 public: 221 /** CCScheduler associated with this director 222 @since v2.0 223 *///声明成员属性 224 CC_PROPERTY(CCScheduler*, m_pScheduler, Scheduler); 225 226 /** CCActionManager associated with this director 227 @since v2.0 228 */ 229 CC_PROPERTY(CCActionManager*, m_pActionManager, ActionManager); 230 231 /** CCTouchDispatcher associated with this director 232 @since v2.0 233 */ 234 CC_PROPERTY(CCTouchDispatcher*, m_pTouchDispatcher, TouchDispatcher); 235 236 /** CCKeypadDispatcher associated with this director 237 @since v2.0 238 */ 239 CC_PROPERTY(CCKeypadDispatcher*, m_pKeypadDispatcher, KeypadDispatcher); 240 241 /** CCAccelerometer associated with this director 242 @since v2.0 243 @js NA 244 @lua NA 245 */ 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 getInstance 254 */ 255 static CCDirector* sharedDirector(void); 256 257 protected: 258 259 void purgeDirector();//清空director 260 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 frame 302 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 events 51 You can enable / disable accelerometer events with this property. 52 @since v0.8.1 53 */ 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 events 59 You can enable / disable accelerometer events with this property. 60 it's new in cocos2d-x 61 */ 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 handler 83 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 sprite 141 * 142 * @param pSpriteFrame A CCSpriteFrame object. It should includes a valid texture and a rect 143 * @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 CCSpriteFrameCache 154 * @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 system 166 * @return true if the sprite is initialized properly, false otherwise. 167 * @js init 168 */ 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 init 182 */ 183 virtual bool initWithFile(const char *pszFilename, const CCRect& rect); 184 185 /// @} end of initializers 186 187 /// @{ 188 /// @name Functions inherited from CCTextureProtocol 189 virtual void setTexture(CCTexture2D *texture); 190 virtual CCTexture2D* getTexture(void); 191 inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = blendFunc; } 192 /** 193 * @js NA 194 */ 195 inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; } 196 /// @} 197 198 /// @{ 199 /// @name Functions inherited from CCNode 200 virtual void setScaleX(float fScaleX); 201 virtual void setScaleY(float fScaleY); 202 /** 203 * @lua NA 204 */ 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 CCNodeRGBA 228 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 methods 239 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 CCSpriteBatchNode 247 * 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 sprite 254 * @warning This method is not recommended for game developers. Sample code for using batch node 255 * @code 256 * 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 * @endcode 261 */ 262 virtual void setBatchNode(CCSpriteBatchNode *pobSpriteBatchNode); 263 264 /// @} end of BatchNode methods 265 266 267 268 /// @{ 269 /// @name Texture methods 270 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 methods 292 293 294 295 /// @{ 296 /// @name Frames methods 297 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 displayed 305 */ 306 virtual bool isFrameDisplayed(CCSpriteFrame *pFrame); 307 308 /** 309 * Returns the current displayed frame. 310 * @js NA 311 */ 312 virtual CCSpriteFrame* displayFrame(void); 313 314 /// @} End of frames methods 315 316 317 /// @{ 318 /// @name Animation methods 319 /** 320 * Changes the display frame with animation name and index. 321 * The animation name will be get from the CCAnimationCache 322 */ 323 virtual void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex); 324 /// @} 325 326 327 /// @{ 328 /// @name Sprite Properties' setter/getters 329 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 NA 345 */ 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 doing 361 */ 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 CCSpriteBatchNode 371 */ 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 CCSpriteBatchNode 376 */ 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 isFlippedX 395 */ 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 isFlippedY 414 */ 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/setters 424 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 CCSpriteSheet 434 // 435 CCTextureAtlas* m_pobTextureAtlas; /// CCSpriteBatchNode texture atlas (weak reference) 436 unsigned int m_uAtlasIndex; /// Absolute (real) Index on the SpriteSheet 437 CCSpriteBatchNode* m_pobBatchNode; /// Used batch node (weak reference) 438 439 bool m_bDirty; /// Whether the sprite needs to be updated 440 bool m_bRecursiveDirty; /// Whether all of the sprite's children needs to be updated 441 bool m_bHasChildren; /// Whether the sprite contains children 442 bool m_bShouldBeHidden; /// should not be drawn because one of the ancestors is not visible 443 CCAffineTransform m_transformToBatch; 444 445 // 446 // Data used when the sprite is self-rendered 447 // 448 ccBlendFunc m_sBlendFunc; /// It's required for CCTextureProtocol inheritance 449 CCTexture2D* m_pobTexture; /// CCTexture2D object that is used to render the sprite 450 451 // 452 // Shared data 453 // 454 455 // texture 456 CCRect m_obRect; /// Retangle of CCTexture2D 457 bool m_bRectRotated; /// Whether the texture is rotated 458 459 // Offset Position (used by Zwoptex) 460 CCPoint m_obOffsetPosition; 461 CCPoint m_obUnflippedOffsetPositionFromCenter; 462 463 // vertex coords, texture coords and color info 464 ccV3F_C4B_T2F_Quad m_sQuad; 465 466 // opacity and RGB protocol 467 bool m_bOpacityModifyRGB; 468 469 // image is flipped 470 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 '