cocod2d-x 之 CCDirector、CCScene、CCSprite

时间:2023-03-09 07:15:38
cocod2d-x 之 CCDirector、CCScene、CCSprite

  CCDirector是控制游戏流程的主要组件。

  

 typedef enum {
/// sets a 2D projection (orthogonal projection)2D投机模式
kCCDirectorProjection2D, /// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500.3D投影
kCCDirectorProjection3D, /// it calls "updateProjection" on the projection delegate.
kCCDirectorProjectionCustom, /// Default projection is 3D projection
kCCDirectorProjectionDefault = kCCDirectorProjection3D,
} ccDirectorProjection; class CC_DLL CCDirector : public CCObject, public TypeInfo
{
public: CCDirector(void);
virtual ~CCDirector(void);
virtual bool init(void);
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CCDirector).name());
return id;
} //获取当前运行的Scene
inline CCScene* getRunningScene(void) { return m_pRunningScene; } /** Get the FPS value *///获取动画绘制间隔
inline double getAnimationInterval(void) { return m_dAnimationInterval; }
/** Set the FPS value. *///设置动画间隔
virtual void setAnimationInterval(double dValue) = ; /** Whether or not to display the FPS on the bottom-left corner *///是否显示状态fps、绘制间隔等
inline bool isDisplayStats(void) { return m_bDisplayStats; }
/** Display the FPS on the bottom-left corner */
inline void setDisplayStats(bool bDisplayStats) { m_bDisplayStats = bDisplayStats; } /** seconds per frame *///每秒钟绘制多少帧
inline float getSecondsPerFrame() { return m_fSecondsPerFrame; } /** Get the CCEGLView, where everything is rendered
* @js NA
*/
inline CCEGLView* getOpenGLView(void) { return m_pobOpenGLView; }
void setOpenGLView(CCEGLView *pobOpenGLView); inline bool isNextDeltaTimeZero(void) { return m_bNextDeltaTimeZero; }
void setNextDeltaTimeZero(bool bNextDeltaTimeZero); /** Whether or not the Director is paused *///是否暂停
inline bool isPaused(void) { return m_bPaused; } /** How many frames were called since the director started *///共绘制了多少帧
inline unsigned int getTotalFrames(void) { return m_uTotalFrames; } /** Sets an OpenGL projection
@since v0.8.2
@js NA
*/
inline ccDirectorProjection getProjection(void) { return m_eProjection; }
void setProjection(ccDirectorProjection kProjection);
/** reshape projection matrix when canvas has been change"*/画布改变后,重塑投影矩阵
void reshapeProjection(const CCSize& newWindowSize); /** Sets the glViewport*/
void setViewport(); /** How many frames were called since the director started */
inline bool isSendCleanupToScene(void) { return m_bSendCleanupToScene; } CCNode* getNotificationNode();
void setNotificationNode(CCNode *node); /** CCDirector delegate. It shall implemente the CCDirectorDelegate protocol
*/
CCDirectorDelegate* getDelegate() const;
void setDelegate(CCDirectorDelegate* pDelegate); // window size,设计分辨率
/** returns the size of the OpenGL view in points.
*/
CCSize getWinSize(void); /** returns the size of the OpenGL view in pixels.
*/
CCSize getWinSizeInPixels(void); /** returns visible size of the OpenGL view in points.
* the value is equal to getWinSize if don't invoke
* CCEGLView::setDesignResolutionSize()
*///openGL的可视区大小,是在 WinSize 之内,保持 FrameSize 的宽高比所能占用的最大区域​
CCSize getVisibleSize(); /** returns visible origin of the OpenGL view in points.
*/
CCPoint getVisibleOrigin(); /** converts a UIKit coordinate to an OpenGL coordinate
Useful to convert (multi) touch coordinates to the current layout (portrait or landscape)
*///将一个点坐标从UI坐标(坐上角为原点)转换为openGL坐标(左下角为坐标),主要用于在点击事件中将点击坐标转换为屏幕坐标
CCPoint convertToGL(const CCPoint& obPoint); /** converts an OpenGL coordinate to a UIKit coordinate
Useful to convert node points to window points for calls such as glScissor
*///将一个点转换为UI坐标的点
CCPoint convertToUI(const CCPoint& obPoint); /// XXX: missing description
float getZEye(void); // Scene Management /** Enters the Director's main loop with the given Scene.
* Call it to run only your FIRST scene.
* Don't call it if there is already a running scene.
*
* It will call pushScene: and then it will call startAnimation
*///加载场景并运行,游戏开始时调用
void runWithScene(CCScene *pScene); /** Suspends the execution of the running scene, pushing it on the stack of suspended scenes.
* The new scene will be executed.
* Try to avoid big stacks of pushed scenes to reduce memory allocation.
* ONLY call it if there is a running scene.
*/
void pushScene(CCScene *pScene); /** Pops out a scene from the queue.
* This scene will replace the running one.
* The running scene will be deleted. If there are no more scenes in the stack the execution is terminated.
* ONLY call it if there is a running scene.
*/
void popScene(void); /** Pops out all scenes from the queue until the root scene in the queue.
* This scene will replace the running one.
* Internally it will call `popToSceneStackLevel(1)`
*/
void popToRootScene(void); /** Pops out all scenes from the queue until it reaches `level`.
If level is 0, it will end the director.
If level is 1, it will pop all scenes until it reaches to root scene.
If level is <= than the current stack level, it won't do anything.
*/
void popToSceneStackLevel(int level); /** Replaces the running scene with a new one. The running scene is terminated.
* ONLY call it if there is a running scene.
*/
void replaceScene(CCScene *pScene); /** Ends the execution, releases the running scene.
It doesn't remove the OpenGL view from its parent. You have to do it manually.
*///游戏结束,释放场景,但未移除openGL view
void end(void); /** Pauses the running scene.
The running scene will be _drawed_ but all scheduled timers will be paused
While paused, the draw rate will be 4 FPS to reduce CPU consumption
*///游戏暂停
void pause(void); /** Resumes the paused scene
The scheduled timers will be activated again.
The "delta time" will be 0 (as if the game wasn't paused)
*///游戏恢复
void resume(void); /** Stops the animation. Nothing will be drawn. The main loop won't be triggered anymore.
If you don't want to pause your animation call [pause] instead.
*///停止动画
virtual void stopAnimation(void) = ; /** The main loop is triggered again.
Call this function only if [stopAnimation] was called earlier
@warning Don't call this function to start the main loop. To run the main loop call runWithScene
*///开始动画
virtual void startAnimation(void) = ; /** Draw the scene.
This method is called every frame. Don't call it manually.
*/
void drawScene(void); // Memory Helper /** Removes cached all cocos2d cached data.
It will purge the CCTextureCache, CCSpriteFrameCache, CCLabelBMFont cache
@since v0.99.3
*///清楚缓存数据,包括纹理、精灵、Label等
void purgeCachedData(void); /** sets the default values based on the CCConfiguration info */
void setDefaultValues(void); // OpenGL Helper /** sets the OpenGL default values */
void setGLDefaultValues(void); /** enables/disables OpenGL alpha blending */
void setAlphaBlending(bool bOn); /** enables/disables OpenGL depth test */
void setDepthTest(bool bOn); virtual void mainLoop(void) = ; /** The size in pixels of the surface. It could be different than the screen size.
High-res devices might have a higher surface size than the screen size.
Only available when compiled using SDK >= 4.0.
@since v0.99.4
*///设置缩放参数
void setContentScaleFactor(float scaleFactor);
float getContentScaleFactor(void); public:
/** CCScheduler associated with this director
@since v2.0
*///声明成员属性
CC_PROPERTY(CCScheduler*, m_pScheduler, Scheduler); /** CCActionManager associated with this director
@since v2.0
*/
CC_PROPERTY(CCActionManager*, m_pActionManager, ActionManager); /** CCTouchDispatcher associated with this director
@since v2.0
*/
CC_PROPERTY(CCTouchDispatcher*, m_pTouchDispatcher, TouchDispatcher); /** CCKeypadDispatcher associated with this director
@since v2.0
*/
CC_PROPERTY(CCKeypadDispatcher*, m_pKeypadDispatcher, KeypadDispatcher); /** CCAccelerometer associated with this director
@since v2.0
@js NA
@lua NA
*/
CC_PROPERTY(CCAccelerometer*, m_pAccelerometer, Accelerometer); /* delta time since last tick to main loop */
CC_PROPERTY_READONLY(float, m_fDeltaTime, DeltaTime); public:
/** returns a shared instance of the director
* @js getInstance
*/
static CCDirector* sharedDirector(void); protected: void purgeDirector();//清空director
bool m_bPurgeDirecotorInNextLoop; // this flag will be set to true in end() void setNextScene(void); void showStats();
void createStatsLabel();
void calculateMPF();
void getFPSImageData(unsigned char** datapointer, unsigned int* length); /** calculates delta time since last time it was called */
void calculateDeltaTime();
protected:
/* The CCEGLView, where everything is rendered */
CCEGLView *m_pobOpenGLView; double m_dAnimationInterval;
double m_dOldAnimationInterval; /* landscape mode ? */
bool m_bLandscape; bool m_bDisplayStats;
float m_fAccumDt;
float m_fFrameRate; CCLabelAtlas *m_pFPSLabel;
CCLabelAtlas *m_pSPFLabel;
CCLabelAtlas *m_pDrawsLabel; /** Whether or not the Director is paused */
bool m_bPaused;//是否暂停 /* How many frames were called since the director started */
/* 开始运行后共渲染了多少帧 */
unsigned int m_uTotalFrames;
unsigned int m_uFrames;
float m_fSecondsPerFrame;//每秒的帧率 /* The running scene */
CCScene *m_pRunningScene;//当前场景 /* will be the next 'runningScene' in the next frame
nextScene is a weak reference. */
CCScene *m_pNextScene;//下一个场景 /* If YES, then "old" scene will receive the cleanup message */
bool m_bSendCleanupToScene;//是否清空前一个场景 /* scheduled scenes */
CCArray* m_pobScenesStack;//scene场景列表 /* last time the main loop was updated */
struct cc_timeval *m_pLastUpdate;//游戏主循环上一次刷新的时间 /* whether or not the next delta time will be zero */
bool m_bNextDeltaTimeZero; /* projection used */
ccDirectorProjection m_eProjection; /* window size in points */
CCSize m_obWinSizeInPoints;//窗口大小 /* content scale factor */
float m_fContentScaleFactor;//缩放 /* store the fps string */
char *m_pszFPS; /* This object will be visited after the scene. Useful to hook a notification node */
CCNode *m_pNotificationNode; /* Projection protocol delegate */
CCDirectorDelegate *m_pProjectionDelegate;//代理 // CCEGLViewProtocol will recreate stats labels to fit visible rect//根据模式重绘画面,用于适配各种屏幕分辨率
friend class CCEGLViewProtocol;
}; 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类似,层也扮演着容器的角色。然而与场景不同的是,层通常包含的是直接呈现在屏幕上的具体内容.

  

 //cocos2d-x-2.2/cocos2dx/layers_scenes_transitions_nodes/CCLayer.h

  class CC_DLL CCLayer : public CCNode, public CCTouchDelegate, public CCAccelerometerDelegate, public CCKeypadDelegate
{
public:
CCLayer();
virtual ~CCLayer();
virtual bool init();
static CCLayer *create(void);
virtual void onEnter();
virtual void onExit();
virtual void onEnterTransitionDidFinish(); // 触摸事件处理函数
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); // 多点触摸
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent); virtual void didAccelerate(CCAcceleration* pAccelerationValue);
void registerScriptAccelerateHandler(int nHandler);
void unregisterScriptAccelerateHandler(void); virtual void registerWithTouchDispatcher(void); /** Register script touch events handler */
//注册触摸事件
virtual void registerScriptTouchHandler(int nHandler, bool bIsMultiTouches = false, int nPriority = INT_MIN, bool bSwallowsTouches = false);
/** Unregister script touch events handler */
virtual void unregisterScriptTouchHandler(void); /** 是否处理触摸事件
*/
virtual bool isTouchEnabled();
virtual void setTouchEnabled(bool value); virtual void setTouchMode(ccTouchesMode mode);
virtual int getTouchMode(); /** priority of the touch events. Default is 0 */
virtual void setTouchPriority(int priority);
virtual int getTouchPriority(); /** whether or not it will receive Accelerometer events
You can enable / disable accelerometer events with this property.
@since v0.8.1
*/
virtual bool isAccelerometerEnabled();
virtual void setAccelerometerEnabled(bool value);
virtual void setAccelerometerInterval(double interval); /** whether or not it will receive keypad events
You can enable / disable accelerometer events with this property.
it's new in cocos2d-x
*/
virtual bool isKeypadEnabled();
virtual void setKeypadEnabled(bool value); /** Register keypad events handler */
void registerScriptKeypadHandler(int nHandler);
/** Unregister keypad events handler */
void unregisterScriptKeypadHandler(void); virtual void keyBackClicked(void);
virtual void keyMenuClicked(void); inline CCTouchScriptHandlerEntry* getScriptTouchHandlerEntry() { return m_pScriptTouchHandlerEntry; };
inline CCScriptHandlerEntry* getScriptKeypadHandlerEntry() { return m_pScriptKeypadHandlerEntry; };
inline CCScriptHandlerEntry* getScriptAccelerateHandlerEntry() { return m_pScriptAccelerateHandlerEntry; };
protected:
bool m_bTouchEnabled;
bool m_bAccelerometerEnabled;
bool m_bKeypadEnabled; private:
// Script touch events handler
CCTouchScriptHandlerEntry* m_pScriptTouchHandlerEntry;
CCScriptHandlerEntry* m_pScriptKeypadHandlerEntry;
CCScriptHandlerEntry* m_pScriptAccelerateHandlerEntry; int m_nTouchPriority;
ccTouchesMode m_eTouchMode; int excuteScriptTouchHandler(int nEventType, CCTouch *pTouch);
int excuteScriptTouchHandler(int nEventType, CCSet *pTouches);
};

  向场景中添加层,我们可以使用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);

 //cocos2d-x-2.2/cocos2dx/sprite_nodes/CCSprite.h
class CC_DLL CCSprite : public CCNodeRGBA, public CCTextureProtocol
#ifdef EMSCRIPTEN
, public CCGLBufferedNode
#endif // EMSCRIPTEN
{
public:
/// @{
/// @name Creators /**
* Creates an empty sprite without texture. You can call setTexture method subsequently.
*
* @return An empty sprite object that is marked as autoreleased.
*/
static CCSprite* create(); /**
* Creates a sprite with an image filename.
*
* After creation, the rect of sprite will be the size of the image,
* and the offset will be (0,0).
*
* @param pszFileName The string which indicates a path to image file, e.g., "scene1/monster.png".
* @return A valid sprite object that is marked as autoreleased.
*/
static CCSprite* create(const char *pszFileName); /**
* Creates a sprite with an image filename and a rect.
*
* @param pszFileName The string wich indicates a path to image file, e.g., "scene1/monster.png"
* @param rect Only the contents inside rect of pszFileName's texture will be applied for this sprite.
* @return A valid sprite object that is marked as autoreleased.
*/
static CCSprite* create(const char *pszFileName, const CCRect& rect); /**
* Creates a sprite with an exsiting texture contained in a CCTexture2D object
* After creation, the rect will be the size of the texture, and the offset will be (0,0).
*
* @param pTexture A pointer to a CCTexture2D object.
* @return A valid sprite object that is marked as autoreleased.
*/
static CCSprite* createWithTexture(CCTexture2D *pTexture); /**
* Creates a sprite with a texture and a rect.
*
* After creation, the offset will be (0,0).
*
* @param pTexture A pointer to an existing CCTexture2D object.
* You can use a CCTexture2D object for many sprites.
* @param rect Only the contents inside the rect of this texture will be applied for this sprite.
* @return A valid sprite object that is marked as autoreleased.
*/
static CCSprite* createWithTexture(CCTexture2D *pTexture, const CCRect& rect); /**
* Creates a sprite with an sprite frame.
*
* @param pSpriteFrame A sprite frame which involves a texture and a rect
* @return A valid sprite object that is marked as autoreleased.
*/
static CCSprite* createWithSpriteFrame(CCSpriteFrame *pSpriteFrame); /**
* Creates a sprite with an sprite frame name.
*
* A CCSpriteFrame will be fetched from the CCSpriteFrameCache by pszSpriteFrameName param.
* If the CCSpriteFrame doesn't exist it will raise an exception.
*
* @param pszSpriteFrameName A null terminated string which indicates the sprite frame name.
* @return A valid sprite object that is marked as autoreleased.
*/
static CCSprite* createWithSpriteFrameName(const char *pszSpriteFrameName); /// @} end of creators group /// @{
/// @name Initializers /**
* Default constructor
* @js ctor
*/
CCSprite(void); /**
* Default destructor
* @js NA
* @lua NA
*/
virtual ~CCSprite(void); /**
* Initializes an empty sprite with nothing init.
*/
virtual bool init(void); /**
* Initializes a sprite with a texture.
*
* After initialization, the rect used will be the size of the texture, and the offset will be (0,0).
*
* @param pTexture A pointer to an existing CCTexture2D object.
* You can use a CCTexture2D object for many sprites.
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithTexture(CCTexture2D *pTexture); /**
* Initializes a sprite with a texture and a rect.
*
* After initialization, the offset will be (0,0).
*
* @param pTexture A pointer to an exisiting CCTexture2D object.
* You can use a CCTexture2D object for many sprites.
* @param rect Only the contents inside rect of this texture will be applied for this sprite.
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect); /**
* Initializes a sprite with a texture and a rect in points, optionally rotated.
*
* After initialization, the offset will be (0,0).
* @note This is the designated initializer.
*
* @param pTexture A CCTexture2D object whose texture will be applied to this sprite.
* @param rect A rectangle assigned the contents of texture.
* @param rotated Whether or not the texture rectangle is rotated.
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect, bool rotated); /**
* Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite
*
* @param pSpriteFrame A CCSpriteFrame object. It should includes a valid texture and a rect
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame); /**
* Initializes a sprite with an sprite frame name.
*
* A CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
* If the CCSpriteFrame doesn't exist it will raise an exception.
*
* @param pszSpriteFrameName A key string that can fected a volid CCSpriteFrame from CCSpriteFrameCache
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName); /**
* Initializes a sprite with an image filename.
*
* This method will find pszFilename from local file system, load its content to CCTexture2D,
* then use CCTexture2D to create a sprite.
* After initialization, the rect used will be the size of the image. The offset will be (0,0).
*
* @param pszFilename The path to an image file in local file system
* @return true if the sprite is initialized properly, false otherwise.
* @js init
*/
virtual bool initWithFile(const char *pszFilename); /**
* Initializes a sprite with an image filename, and a rect.
*
* This method will find pszFilename from local file system, load its content to CCTexture2D,
* then use CCTexture2D to create a sprite.
* After initialization, the offset will be (0,0).
*
* @param pszFilename The path to an image file in local file system.
* @param rect The rectangle assigned the content area from texture.
* @return true if the sprite is initialized properly, false otherwise.
* @js init
*/
virtual bool initWithFile(const char *pszFilename, const CCRect& rect); /// @} end of initializers /// @{
/// @name Functions inherited from CCTextureProtocol
virtual void setTexture(CCTexture2D *texture);
virtual CCTexture2D* getTexture(void);
inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = blendFunc; }
/**
* @js NA
*/
inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; }
/// @} /// @{
/// @name Functions inherited from CCNode
virtual void setScaleX(float fScaleX);
virtual void setScaleY(float fScaleY);
/**
* @lua NA
*/
virtual void setPosition(const CCPoint& pos);
virtual void setRotation(float fRotation);
virtual void setRotationX(float fRotationX);
virtual void setRotationY(float fRotationY);
virtual void setSkewX(float sx);
virtual void setSkewY(float sy);
virtual void removeChild(CCNode* pChild, bool bCleanup);
virtual void removeAllChildrenWithCleanup(bool bCleanup);
virtual void reorderChild(CCNode *pChild, int zOrder);
virtual void addChild(CCNode *pChild);
virtual void addChild(CCNode *pChild, int zOrder);
virtual void addChild(CCNode *pChild, int zOrder, int tag);
virtual void sortAllChildren();
virtual void setScale(float fScale);
virtual void setVertexZ(float fVertexZ);
virtual void setAnchorPoint(const CCPoint& anchor);
virtual void ignoreAnchorPointForPosition(bool value);
virtual void setVisible(bool bVisible);
virtual void draw(void);
/// @} /// @{
/// @name Functions inherited from CCNodeRGBA
virtual void setColor(const ccColor3B& color3);
virtual void updateDisplayedColor(const ccColor3B& parentColor);
virtual void setOpacity(GLubyte opacity);
virtual void setOpacityModifyRGB(bool modify);
virtual bool isOpacityModifyRGB(void);
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
/// @} /// @{
/// @name BatchNode methods /**
* Updates the quad according the rotation, position, scale values.
*/
virtual void updateTransform(void); /**
* Returns the batch node object if this sprite is rendered by CCSpriteBatchNode
*
* @return The CCSpriteBatchNode object if this sprite is rendered by CCSpriteBatchNode,
* NULL if the sprite isn't used batch node.
*/
virtual CCSpriteBatchNode* getBatchNode(void);
/**
* Sets the batch node to sprite
* @warning This method is not recommended for game developers. Sample code for using batch node
* @code
* CCSpriteBatchNode *batch = CCSpriteBatchNode::create("Images/grossini_dance_atlas.png", 15);
* CCSprite *sprite = CCSprite::createWithTexture(batch->getTexture(), CCRectMake(0, 0, 57, 57));
* batch->addChild(sprite);
* layer->addChild(batch);
* @endcode
*/
virtual void setBatchNode(CCSpriteBatchNode *pobSpriteBatchNode); /// @} end of BatchNode methods /// @{
/// @name Texture methods /**
* Updates the texture rect of the CCSprite in points.
* It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size.
*/
virtual void setTextureRect(const CCRect& rect); /**
* Sets the texture rect, rectRotated and untrimmed size of the CCSprite in points.
* It will update the texture coordinates and the vertex rectangle.
*/
virtual void setTextureRect(const CCRect& rect, bool rotated, const CCSize& untrimmedSize); /**
* Sets the vertex rect.
* It will be called internally by setTextureRect.
* Useful if you want to create 2x images from SD images in Retina Display.
* Do not call it manually. Use setTextureRect instead.
*/
virtual void setVertexRect(const CCRect& rect); /// @} end of texture methods /// @{
/// @name Frames methods /**
* Sets a new display frame to the CCSprite.
*/
virtual void setDisplayFrame(CCSpriteFrame *pNewFrame); /**
* Returns whether or not a CCSpriteFrame is being displayed
*/
virtual bool isFrameDisplayed(CCSpriteFrame *pFrame); /**
* Returns the current displayed frame.
* @js NA
*/
virtual CCSpriteFrame* displayFrame(void); /// @} End of frames methods /// @{
/// @name Animation methods
/**
* Changes the display frame with animation name and index.
* The animation name will be get from the CCAnimationCache
*/
virtual void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex);
/// @} /// @{
/// @name Sprite Properties' setter/getters /**
* Whether or not the Sprite needs to be updated in the Atlas.
*
* @return true if the sprite needs to be updated in the Atlas, false otherwise.
*/
inline virtual bool isDirty(void) { return m_bDirty; } /**
* Makes the Sprite to be updated in the Atlas.
*/
inline virtual void setDirty(bool bDirty) { m_bDirty = bDirty; } /**
* Returns the quad (tex coords, vertex coords and color) information.
* @js NA
*/
inline ccV3F_C4B_T2F_Quad getQuad(void) { return m_sQuad; } /**
* Returns whether or not the texture rectangle is rotated.
*/
inline bool isTextureRectRotated(void) { return m_bRectRotated; } /**
* Returns the index used on the TextureAtlas.
*/
inline unsigned int getAtlasIndex(void) { return m_uAtlasIndex; } /**
* Sets the index used on the TextureAtlas.
* @warning Don't modify this value unless you know what you are doing
*/
inline void setAtlasIndex(unsigned int uAtlasIndex) { m_uAtlasIndex = uAtlasIndex; } /**
* Returns the rect of the CCSprite in points
*/
inline const CCRect& getTextureRect(void) { return m_obRect; } /**
* Gets the weak reference of the CCTextureAtlas when the sprite is rendered using via CCSpriteBatchNode
*/
inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas; } /**
* Sets the weak reference of the CCTextureAtlas when the sprite is rendered using via CCSpriteBatchNode
*/
inline void setTextureAtlas(CCTextureAtlas *pobTextureAtlas) { m_pobTextureAtlas = pobTextureAtlas; } /**
* Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex.
*/
inline const CCPoint& getOffsetPosition(void) { return m_obOffsetPosition; } /**
* Returns the flag which indicates whether the sprite is flipped horizontally or not.
*
* It only flips the texture of the sprite, and not the texture of the sprite's children.
* Also, flipping the texture doesn't alter the anchorPoint.
* If you want to flip the anchorPoint too, and/or to flip the children too use:
* sprite->setScaleX(sprite->getScaleX() * -1);
*
* @return true if the sprite is flipped horizaontally, false otherwise.
* @js isFlippedX
*/
bool isFlipX(void);
/**
* Sets whether the sprite should be flipped horizontally or not.
*
* @param bFlipX true if the sprite should be flipped horizaontally, false otherwise.
*/
void setFlipX(bool bFlipX); /**
* Return the flag which indicates whether the sprite is flipped vertically or not.
*
* It only flips the texture of the sprite, and not the texture of the sprite's children.
* Also, flipping the texture doesn't alter the anchorPoint.
* If you want to flip the anchorPoint too, and/or to flip the children too use:
* sprite->setScaleY(sprite->getScaleY() * -1);
*
* @return true if the sprite is flipped vertically, flase otherwise.
* @js isFlippedY
*/
bool isFlipY(void);
/**
* Sets whether the sprite should be flipped vertically or not.
*
* @param bFlipY true if the sprite should be flipped vertically, flase otherwise.
*/
void setFlipY(bool bFlipY); /// @} End of Sprite properties getter/setters protected:
void updateColor(void);
virtual void setTextureCoords(CCRect rect);
virtual void updateBlendFunc(void);
virtual void setReorderChildDirtyRecursively(void);
virtual void setDirtyRecursively(bool bValue); //
// Data used when the sprite is rendered using a CCSpriteSheet
//
CCTextureAtlas* m_pobTextureAtlas; /// CCSpriteBatchNode texture atlas (weak reference)
unsigned int m_uAtlasIndex; /// Absolute (real) Index on the SpriteSheet
CCSpriteBatchNode* m_pobBatchNode; /// Used batch node (weak reference) bool m_bDirty; /// Whether the sprite needs to be updated
bool m_bRecursiveDirty; /// Whether all of the sprite's children needs to be updated
bool m_bHasChildren; /// Whether the sprite contains children
bool m_bShouldBeHidden; /// should not be drawn because one of the ancestors is not visible
CCAffineTransform m_transformToBatch; //
// Data used when the sprite is self-rendered
//
ccBlendFunc m_sBlendFunc; /// It's required for CCTextureProtocol inheritance
CCTexture2D* m_pobTexture; /// CCTexture2D object that is used to render the sprite //
// Shared data
// // texture
CCRect m_obRect; /// Retangle of CCTexture2D
bool m_bRectRotated; /// Whether the texture is rotated // Offset Position (used by Zwoptex)
CCPoint m_obOffsetPosition;
CCPoint m_obUnflippedOffsetPositionFromCenter; // vertex coords, texture coords and color info
ccV3F_C4B_T2F_Quad m_sQuad; // opacity and RGB protocol
bool m_bOpacityModifyRGB; // image is flipped
bool m_bFlipX; /// Whether the sprite is flipped horizaontally or not.
bool m_bFlipY; /// Whether the sprite is flipped vertically or not.
}; CCSprite.h

  CCNode与坐标系

  Cocos2d-x采用了场景、层、精灵的层次结构来组织游戏元素,与此同时,这个层次结构还对应了游戏的渲染层次,因此游戏元素可以组织成树形结构,称作渲染树。Cocos2d-x把渲染树上的每一个游戏元素抽象为一个节点,即CCNode。一切游戏元素都继承自CCNode,因此它们都具有CCNode所提供的特性。

 //cocos2d-x-2.2/cocos2dx/base_nodes/CCNode.h

 enum {
kCCNodeTagInvalid = -,
}; enum {
kCCNodeOnEnter,
kCCNodeOnExit,
kCCNodeOnEnterTransitionDidFinish,
kCCNodeOnExitTransitionDidStart,
kCCNodeOnCleanup
}; class CC_DLL CCNode : public CCObject
{
public:
/// @{
/// @name Constructor, Distructor and Initializers /**
* Default constructor
* @js ctor
*/
CCNode(void); /**
* Default destructor
* @js NA
* @lua NA
*/
virtual ~CCNode(void); /**
* Initializes the instance of CCNode
* @return Whether the initialization was successful.
*/
virtual bool init();
/**
* Allocates and initializes a node.
* @return A initialized node which is marked as "autorelease".
*/
static CCNode * create(void); /**
* Gets the description string. It makes debugging easier.
* @return A string terminated with '\0'
* @js NA
*/
const char* description(void); /// @} end of initializers /// @{
/// @name Setters & Getters for Graphic Peroperties /**
* Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array.
*
* The Z order of node is relative to its "brothers": children of the same parent.
* It's nothing to do with OpenGL's z vertex. This one only affects the draw order of nodes in cocos2d.
* The larger number it is, the later this node will be drawn in each message loop.
* Please refer to setVertexZ(float) for the difference.
*
* @param nZOrder Z order of this node.
*/
virtual void setZOrder(int zOrder);
/**
* Sets the z order which stands for the drawing order
*
* This is an internal method. Don't call it outside the framework.
* The difference between setZOrder(int) and _setOrder(int) is:
* - _setZOrder(int) is a pure setter for m_nZOrder memeber variable
* - setZOrder(int) firstly changes m_nZOrder, then recorder this node in its parent's chilren array.
*/
virtual void _setZOrder(int z);
/**
* Gets the Z order of this node.
*
* @see setZOrder(int)
*
* @return The Z order.
*/
virtual int getZOrder(); /**
* Sets the real OpenGL Z vertex.
*
* Differences between openGL Z vertex and cocos2d Z order:
* - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children
* - OpenGL Z might require to set 2D projection
* - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0
*
* @warning Use it at your own risk since it might break the cocos2d parent-children z order
*
* @param fVertexZ OpenGL Z vertex of this node.
*/
virtual void setVertexZ(float vertexZ);
/**
* Gets OpenGL Z vertex of this node.
*
* @see setVertexZ(float)
*
* @return OpenGL Z vertex of this node
*/
virtual float getVertexZ(); /**
* Changes the scale factor on X axis of this node
*
* The deafult value is 1.0 if you haven't changed it before
*
* @param fScaleX The scale factor on X axis.
*/
virtual void setScaleX(float fScaleX);
/**
* Returns the scale factor on X axis of this node
*
* @see setScaleX(float)
*
* @return The scale factor on X axis.
*/
virtual float getScaleX(); /**
* Changes the scale factor on Y axis of this node
*
* The Default value is 1.0 if you haven't changed it before.
*
* @param fScaleY The scale factor on Y axis.
*/
virtual void setScaleY(float fScaleY);
/**
* Returns the scale factor on Y axis of this node
*
* @see setScaleY(float)
*
* @return The scale factor on Y axis.
*/
virtual float getScaleY(); /**
* Changes both X and Y scale factor of the node.
*
* 1.0 is the default scale factor. It modifies the X and Y scale at the same time.
*
* @param scale The scale factor for both X and Y axis.
*/
virtual void setScale(float scale);
/**
* Gets the scale factor of the node, when X and Y have the same scale factor.
*
* @warning Assert when m_fScaleX != m_fScaleY.
* @see setScale(float)
*
* @return The scale factor of the node.
*/
virtual float getScale(); /**
* Changes both X and Y scale factor of the node.
*
* 1.0 is the default scale factor. It modifies the X and Y scale at the same time.
*
* @param fScaleX The scale factor on X axis.
* @param fScaleY The scale factor on Y axis.
*/
virtual void setScale(float fScaleX,float fScaleY); /**
* Changes the position (x,y) of the node in OpenGL coordinates
*
* Usually we use ccp(x,y) to compose CCPoint object.
* The original point (0,0) is at the left-bottom corner of screen.
* For example, this codesnip sets the node in the center of screen.
* @code
* CCSize size = CCDirector::sharedDirector()->getWinSize();
* node->setPosition( ccp(size.width/2, size.height/2) )
* @endcode
*
* @param position The position (x,y) of the node in OpenGL coordinates
* @js NA
*/
virtual void setPosition(const CCPoint &position);
/**
* Gets the position (x,y) of the node in OpenGL coordinates
*
* @see setPosition(const CCPoint&)
*
* @return The position (x,y) of the node in OpenGL coordinates
*/
virtual const CCPoint& getPosition();
/**
* Sets position in a more efficient way.
*
* Passing two numbers (x,y) is much efficient than passing CCPoint object.
* This method is binded to lua and javascript.
* Passing a number is 10 times faster than passing a object from lua to c++
*
* @code
* // sample code in lua
* local pos = node::getPosition() -- returns CCPoint object from C++
* node:setPosition(x, y) -- pass x, y coordinate to C++
* @endcode
*
* @param x X coordinate for position
* @param y Y coordinate for position
* @js NA
*/
virtual void setPosition(float x, float y);
/**
* Gets position in a more efficient way, returns two number instead of a CCPoint object
*
* @see setPosition(float, float)
*/
virtual void getPosition(float* x, float* y);
/**
* Gets/Sets x or y coordinate individually for position.
* These methods are used in Lua and Javascript Bindings
*/
virtual void setPositionX(float x);
virtual float getPositionX(void);
virtual void setPositionY(float y);
virtual float getPositionY(void); /**
* Changes the X skew angle of the node in degrees.
*
* This angle describes the shear distortion in the X direction.
* Thus, it is the angle between the Y axis and the left edge of the shape
* The default skewX angle is 0. Positive values distort the node in a CW direction.
*
* @param fSkewX The X skew angle of the node in degrees.
*/
virtual void setSkewX(float fSkewX);
/**
* Returns the X skew angle of the node in degrees.
*
* @see setSkewX(float)
*
* @return The X skew angle of the node in degrees.
*/
virtual float getSkewX(); /**
* Changes the Y skew angle of the node in degrees.
*
* This angle describes the shear distortion in the Y direction.
* Thus, it is the angle between the X axis and the bottom edge of the shape
* The default skewY angle is 0. Positive values distort the node in a CCW direction.
*
* @param fSkewY The Y skew angle of the node in degrees.
*/
virtual void setSkewY(float fSkewY);
/**
* Returns the Y skew angle of the node in degrees.
*
* @see setSkewY(float)
*
* @return The Y skew angle of the node in degrees.
*/
virtual float getSkewY(); /**
* Sets the anchor point in percent.
*
* anchorPoint is the point around which all transformations and positioning manipulations take place.
* It's like a pin in the node where it is "attached" to its parent.
* The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
* But you can use values higher than (1,1) and lower than (0,0) too.
* The default anchorPoint is (0.5,0.5), so it starts in the center of the node.
*
* @param anchorPoint The anchor point of node.
*/
virtual void setAnchorPoint(const CCPoint& anchorPoint);
/**
* Returns the anchor point in percent.
*
* @see setAnchorPoint(const CCPoint&)
*
* @return The anchor point of node.
*/
virtual const CCPoint& getAnchorPoint();
/**
* Returns the anchorPoint in absolute pixels.
*
* @warning You can only read it. If you wish to modify it, use anchorPoint instead.
* @see getAnchorPoint()
*
* @return The anchor point in absolute pixels.
*/
virtual const CCPoint& getAnchorPointInPoints(); /**
* Sets the untransformed size of the node.
*
* The contentSize remains the same no matter the node is scaled or rotated.
* All nodes has a size. Layer and Scene has the same size of the screen.
*
* @param contentSize The untransformed size of the node.
*/
virtual void setContentSize(const CCSize& contentSize);
/**
* Returns the untransformed size of the node.
*
* @see setContentSize(const CCSize&)
*
* @return The untransformed size of the node.
*/
virtual const CCSize& getContentSize() const; /**
* Sets whether the node is visible
*
* The default value is true, a node is default to visible
*
* @param visible true if the node is visible, false if the node is hidden.
*/
virtual void setVisible(bool visible);
/**
* Determines if the node is visible
*
* @see setVisible(bool)
*
* @return true if the node is visible, false if the node is hidden.
*/
virtual bool isVisible(); /**
* Sets the rotation (angle) of the node in degrees.
*
* 0 is the default rotation angle.
* Positive values rotate node clockwise, and negative values for anti-clockwise.
*
* @param fRotation The roration of the node in degrees.
*/
virtual void setRotation(float fRotation);
/**
* Returns the rotation of the node in degrees.
*
* @see setRotation(float)
*
* @return The rotation of the node in degrees.
*/
virtual float getRotation(); /**
* Sets the X rotation (angle) of the node in degrees which performs a horizontal rotational skew.
*
* 0 is the default rotation angle.
* Positive values rotate node clockwise, and negative values for anti-clockwise.
*
* @param fRotationX The X rotation in degrees which performs a horizontal rotational skew.
*/
virtual void setRotationX(float fRotaionX);
/**
* Gets the X rotation (angle) of the node in degrees which performs a horizontal rotation skew.
*
* @see setRotationX(float)
*
* @return The X rotation in degrees.
*/
virtual float getRotationX(); /**
* Sets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew.
*
* 0 is the default rotation angle.
* Positive values rotate node clockwise, and negative values for anti-clockwise.
*
* @param fRotationY The Y rotation in degrees.
*/
virtual void setRotationY(float fRotationY);
/**
* Gets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew.
*
* @see setRotationY(float)
*
* @return The Y rotation in degrees.
*/
virtual float getRotationY(); /**
* Sets the arrival order when this node has a same ZOrder with other children.
*
* A node which called addChild subsequently will take a larger arrival order,
* If two children have the same Z order, the child with larger arrival order will be drawn later.
*
* @warning This method is used internally for zOrder sorting, don't change this manually
*
* @param uOrderOfArrival The arrival order.
*/
virtual void setOrderOfArrival(unsigned int uOrderOfArrival);
/**
* Returns the arrival order, indecates which children is added previously.
*
* @see setOrderOfArrival(unsigned int)
*
* @return The arrival order.
*/
virtual unsigned int getOrderOfArrival(); /**
* Sets the state of OpenGL server side.
*
* @param glServerState The state of OpenGL server side.
* @js NA
*/
virtual void setGLServerState(ccGLServerState glServerState);
/**
* Returns the state of OpenGL server side.
*
* @return The state of OpenGL server side.
* @js NA
*/
virtual ccGLServerState getGLServerState(); /**
* Sets whether the anchor point will be (0,0) when you position this node.
*
* This is an internal method, only used by CCLayer and CCScene. Don't call it outside framework.
* The default value is false, while in CCLayer and CCScene are true
*
* @param ignore true if anchor point will be (0,0) when you position this node
* @todo This method shoud be renamed as setIgnoreAnchorPointForPosition(bool) or something with "set"
*/
virtual void ignoreAnchorPointForPosition(bool ignore);
/**
* Gets whether the anchor point will be (0,0) when you position this node.
*
* @see ignoreAnchorPointForPosition(bool)
*
* @return true if the anchor point will be (0,0) when you position this node.
*/
virtual bool isIgnoreAnchorPointForPosition(); /// @} end of Setters & Getters for Graphic Peroperties /// @{
/// @name Children and Parent /**
* Adds a child to the container with z-order as 0.
*
* If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
*
* @param child A child node
*/
virtual void addChild(CCNode * child);
/**
* Adds a child to the container with a z-order
*
* If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
*
* @param child A child node
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int)
*/
virtual void addChild(CCNode * child, int zOrder);
/**
* Adds a child to the container with z order and tag
*
* If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
*
* @param child A child node
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int)
* @param tag A interger to identify the node easily. Please refer to setTag(int)
*/
virtual void addChild(CCNode* child, int zOrder, int tag);
/**
* Gets a child from the container with its tag
*
* @param tag An identifier to find the child node.
*
* @return a CCNode object whose tag equals to the input parameter
*/
CCNode * getChildByTag(int tag);
/**
* Return an array of children
*
* Composing a "tree" structure is a very important feature of CCNode
* Here's a sample code of traversing children array:
* @code
* CCNode* node = NULL;
* CCARRAY_FOREACH(parent->getChildren(), node)
* {
* node->setPosition(0,0);
* }
* @endcode
* This sample code traverses all children nodes, and set theie position to (0,0)
*
* @return An array of children
*/
virtual CCArray* getChildren(); /**
* Get the amount of children.
*
* @return The amount of children.
*/
unsigned int getChildrenCount(void) const; /**
* Sets the parent node
*
* @param parent A pointer to the parnet node
*/
virtual void setParent(CCNode* parent);
/**
* Returns a pointer to the parent node
*
* @see setParent(CCNode*)
*
* @returns A pointer to the parnet node
*/
virtual CCNode* getParent(); ////// REMOVES ////// /**
* Removes this node itself from its parent node with a cleanup.
* If the node orphan, then nothing happens.
* @see removeFromParentAndCleanup(bool)
*/
virtual void removeFromParent();
/**
* Removes this node itself from its parent node.
* If the node orphan, then nothing happens.
* @param cleanup true if all actions and callbacks on this node should be removed, false otherwise.
* @js removeFromParent
*/
virtual void removeFromParentAndCleanup(bool cleanup);
/**
* Removes a child from the container with a cleanup
*
* @see removeChild(CCNode, bool)
*
* @param child The child node which will be removed.
*/
virtual void removeChild(CCNode* child);
/**
* Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.
*
* @param child The child node which will be removed.
* @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise.
*/
virtual void removeChild(CCNode* child, bool cleanup);
/**
* Removes a child from the container by tag value with a cleanup.
*
* @see removeChildByTag(int, bool)
*
* @param tag An interger number that identifies a child node
*/
virtual void removeChildByTag(int tag);
/**
* Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter
*
* @param tag An interger number that identifies a child node
* @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise.
*/
virtual void removeChildByTag(int tag, bool cleanup);
/**
* Removes all children from the container with a cleanup.
*
* @see removeAllChildrenWithCleanup(bool)
*/
virtual void removeAllChildren();
/**
* Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter.
*
* @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise.
* @js removeAllChildren
*/
virtual void removeAllChildrenWithCleanup(bool cleanup); /**
* Reorders a child according to a new z value.
*
* @param child An already added child node. It MUST be already added.
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int)
*/
virtual void reorderChild(CCNode * child, int zOrder); /**
* Sorts the children array once before drawing, instead of every time when a child is added or reordered.
* This appraoch can improves the performance massively.
* @note Don't call this manually unless a child added needs to be removed in the same frame
*/
virtual void sortAllChildren(); /// @} end of Children and Parent /// @{
/// @name Grid object for effects /**
* Returns a grid object that is used when applying effects
*
* @return A CCGrid object that is used when applying effects
* @js NA
*/
virtual CCGridBase* getGrid();
/**
* Changes a grid object that is used when applying effects
*
* @param A CCGrid object that is used when applying effects
*/
virtual void setGrid(CCGridBase *pGrid); /// @} end of Grid /// @{
/// @name Tag & User data /**
* Returns a tag that is used to identify the node easily.
*
* You can set tags to node then identify them easily.
* @code
* #define TAG_PLAYER 1
* #define TAG_MONSTER 2
* #define TAG_BOSS 3
* // set tags
* node1->setTag(TAG_PLAYER);
* node2->setTag(TAG_MONSTER);
* node3->setTag(TAG_BOSS);
* parent->addChild(node1);
* parent->addChild(node2);
* parent->addChild(node3);
* // identify by tags
* CCNode* node = NULL;
* CCARRAY_FOREACH(parent->getChildren(), node)
* {
* switch(node->getTag())
* {
* case TAG_PLAYER:
* break;
* case TAG_MONSTER:
* break;
* case TAG_BOSS:
* break;
* }
* }
* @endcode
*
* @return A interger that identifies the node.
*/
virtual int getTag() const;
/**
* Changes the tag that is used to identify the node easily.
*
* Please refer to getTag for the sample code.
*
* @param A interger that indentifies the node.
*/
virtual void setTag(int nTag); /**
* Returns a custom user data pointer
*
* You can set everything in UserData pointer, a data block, a structure or an object.
*
* @return A custom user data pointer
* @js NA
*/
virtual void* getUserData();
/**
* Sets a custom user data pointer
*
* You can set everything in UserData pointer, a data block, a structure or an object, etc.
* @warning Don't forget to release the memroy manually,
* especially before you change this data pointer, and before this node is autoreleased.
*
* @return A custom user data pointer
* @js NA
*/
virtual void setUserData(void *pUserData); /**
* Returns a user assigned CCObject
*
* Similar to userData, but instead of holding a void* it holds an object
*
* @return A user assigned CCObject
* @js NA
*/
virtual CCObject* getUserObject();
/**
* Returns a user assigned CCObject
*
* Similar to UserData, but instead of holding a void* it holds an object.
* The UserObject will be retained once in this method,
* and the previous UserObject (if existed) will be relese.
* The UserObject will be released in CCNode's destructure.
*
* @param A user assigned CCObject
*/
virtual void setUserObject(CCObject *pUserObject); /// @} end of Tag & User Data /// @{
/// @name Shader Program
/**
* Return the shader program currently used for this node
*
* @return The shader program currelty used for this node
*/
virtual CCGLProgram* getShaderProgram();
/**
* Sets the shader program for this node
*
* Since v2.0, each rendering node must set its shader program.
* It should be set in initialize phase.
* @code
* node->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor));
* @endcode
*
* @param The shader program which fetchs from CCShaderCache.
*/
virtual void setShaderProgram(CCGLProgram *pShaderProgram);
/// @} end of Shader Program /**
* Returns a camera object that lets you move the node using a gluLookAt
*
* @code
* CCCamera* camera = node->getCamera();
* camera->setEyeXYZ(0, 0, 415/2);
* camera->setCenterXYZ(0, 0, 0);
* @endcode
*
* @return A CCCamera object that lets you move the node using a gluLookAt
*/
virtual CCCamera* getCamera(); /**
* Returns whether or not the node accepts event callbacks.
*
* Running means the node accept event callbacks like onEnter(), onExit(), update()
*
* @return Whether or not the node is running.
*/
virtual bool isRunning(); /// @{
/// @name Script Bindings for lua /**
* Registers a script function that will be called in onEnter() & onExit() seires functions.
*
* This handler will be removed automatically after onExit() called.
* @code
* -- lua sample
* local function sceneEventHandler(eventType)
* if eventType == kCCNodeOnEnter then
* -- do something
* elseif evetType == kCCNodeOnExit then
* -- do something
* end
* end
* scene::registerScriptHandler(sceneEventHandler)
* @endcode
*
* @warning This method is for internal usage, don't call it manually.
* @todo Perhaps we should rename it to get/set/removeScriptHandler acoording to the function name style.
*
* @param handler A number that indicates a lua function.
*/
virtual void registerScriptHandler(int handler);
/**
* Unregisters a script function that will be called in onEnter() & onExit() series functions.
*
* @see registerScriptHandler(int)
*/
virtual void unregisterScriptHandler(void);
/**
* Gets script handler for onEnter/onExit event.
* This is an internal method. g
* @see registerScriptHandler(int)
*
* @return A number that indicates a lua function.
*/
inline int getScriptHandler() { return m_nScriptHandler; }; /**
* Schedules for lua script.
* @js NA
*/
void scheduleUpdateWithPriorityLua(int nHandler, int priority); /// @} end Script Bindings /// @{
/// @name Event Callbacks /**
* Event callback that is invoked every time when CCNode enters the 'stage'.
* If the CCNode enters the 'stage' with a transition, this event is called when the transition starts.
* During onEnter you can't access a "sister/brother" node.
* If you override onEnter, you shall call its parent's one, e.g., CCNode::onEnter().
* @js NA
* @lua NA
*/
virtual void onEnter(); /** Event callback that is invoked when the CCNode enters in the 'stage'.
* If the CCNode enters the 'stage' with a transition, this event is called when the transition finishes.
* If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. CCNode::onEnterTransitionDidFinish()
* @js NA
* @lua NA
*/
virtual void onEnterTransitionDidFinish(); /**
* Event callback that is invoked every time the CCNode leaves the 'stage'.
* If the CCNode leaves the 'stage' with a transition, this event is called when the transition finishes.
* During onExit you can't access a sibling node.
* If you override onExit, you shall call its parent's one, e.g., CCNode::onExit().
* @js NA
* @lua NA
*/
virtual void onExit(); /**
* Event callback that is called every time the CCNode leaves the 'stage'.
* If the CCNode leaves the 'stage' with a transition, this callback is called when the transition starts.
* @js NA
* @lua NA
*/
virtual void onExitTransitionDidStart(); /// @} end of event callbacks. /**
* Stops all running actions and schedulers
*/
virtual void cleanup(void); /**
* Override this method to draw your own node.
* The following GL states will be enabled by default:
* - glEnableClientState(GL_VERTEX_ARRAY);
* - glEnableClientState(GL_COLOR_ARRAY);
* - glEnableClientState(GL_TEXTURE_COORD_ARRAY);
* - glEnable(GL_TEXTURE_2D);
* AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE
* But if you enable any other GL state, you should disable it after drawing your node.
*/
virtual void draw(void); /**
* Visits this node's children and draw them recursively.
*/
virtual void visit(void); /**
* Returns a "local" axis aligned bounding box of the node.
* The returned box is relative only to its parent.
*
* @note This method returns a temporaty variable, so it can't returns const CCRect&
* @todo Rename to getBoundingBox() in the future versions.
*
* @return A "local" axis aligned boudning box of the node.
* @js getBoundingBox
*/
CCRect boundingBox(void); /// @{
/// @name Actions /**
* Sets the CCActionManager object that is used by all actions.
*
* @warning If you set a new CCActionManager, then previously created actions will be removed.
*
* @param actionManager A CCActionManager object that is used by all actions.
*/
virtual void setActionManager(CCActionManager* actionManager);
/**
* Gets the CCActionManager object that is used by all actions.
* @see setActionManager(CCActionManager*)
* @return A CCActionManager object.
*/
virtual CCActionManager* getActionManager(); /**
* Executes an action, and returns the action that is executed.
*
* This node becomes the action's target. Refer to CCAction::getTarget()
* @warning Actions don't retain their target.
*
* @return An Action pointer
*/
CCAction* runAction(CCAction* action); /**
* Stops and removes all actions from the running action list .
*/
void stopAllActions(void); /**
* Stops and removes an action from the running action list.
*
* @param An action object to be removed.
*/
void stopAction(CCAction* action); /**
* Removes an action from the running action list by its tag.
*
* @param A tag that indicates the action to be removed.
*/
void stopActionByTag(int tag); /**
* Gets an action from the running action list by its tag.
*
* @see setTag(int), getTag().
*
* @return The action object with the given tag.
*/
CCAction* getActionByTag(int tag); /**
* Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays).
*
* Composable actions are counted as 1 action. Example:
* If you are running 1 Sequence of 7 actions, it will return 1.
* If you are running 7 Sequences of 2 actions, it will return 7.
* @todo Rename to getNumberOfRunningActions()
*
* @return The number of actions that are running plus the ones that are schedule to run
*/
unsigned int numberOfRunningActions(void); /// @} end of Actions /// @{
/// @name Scheduler and Timer /**
* Sets a CCScheduler object that is used to schedule all "updates" and timers.
*
* @warning If you set a new CCScheduler, then previously created timers/update are going to be removed.
* @param scheduler A CCShdeduler object that is used to schedule all "update" and timers.
* @js NA
*/
virtual void setScheduler(CCScheduler* scheduler);
/**
* Gets a CCSheduler object.
*
* @see setScheduler(CCScheduler*)
* @return A CCScheduler object.
* @js NA
*/
virtual CCScheduler* getScheduler(); /**
* Checks whether a selector is scheduled.
*
* @param selector A function selector
* @return Whether the funcion selector is scheduled.
* @js NA
* @lua NA
*/
bool isScheduled(SEL_SCHEDULE selector); /**
* Schedules the "update" method.
*
* It will use the order number 0. This method will be called every frame.
* Scheduled methods with a lower order value will be called before the ones that have a higher order value.
* Only one "update" method could be scheduled per node.
* @lua NA
*/
void scheduleUpdate(void); /**
* Schedules the "update" method with a custom priority.
*
* This selector will be called every frame.
* Scheduled methods with a lower priority will be called before the ones that have a higher value.
* Only one "update" selector could be scheduled per node (You can't have 2 'update' selectors).
* @lua NA
*/
void scheduleUpdateWithPriority(int priority); /*
* Unschedules the "update" method.
* @see scheduleUpdate();
*/
void unscheduleUpdate(void); /**
* Schedules a custom selector.
*
* If the selector is already scheduled, then the interval parameter will be updated without scheduling it again.
* @code
* // firstly, implement a schedule function
* void MyNode::TickMe(float dt);
* // wrap this function into a selector via schedule_selector marco.
* this->schedule(schedule_selector(MyNode::TickMe), 0, 0, 0);
* @endcode
*
* @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead.
* @param repeat The selector will be excuted (repeat + 1) times, you can use kCCRepeatForever for tick infinitely.
* @param delay The amount of time that the first tick will wait before execution.
* @lua NA
*/
void schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay); /**
* Schedules a custom selector with an interval time in seconds.
* @see schedule(SEL_SCHEDULE, float, unsigned int, float)
*
* @param selector A function wrapped as a selector
* @param interval Callback interval time in seconds. 0 means tick every frame,
* @lua NA
*/
void schedule(SEL_SCHEDULE selector, float interval); /**
* Schedules a selector that runs only once, with a delay of 0 or larger
* @see schedule(SEL_SCHEDULE, float, unsigned int, float)
*
* @param selector A function wrapped as a selector
* @param delay The amount of time that the first tick will wait before execution.
* @lua NA
*/
void scheduleOnce(SEL_SCHEDULE selector, float delay); /**
* Schedules a custom selector, the scheduled selector will be ticked every frame
* @see schedule(SEL_SCHEDULE, float, unsigned int, float)
*
* @param selector A function wrapped as a selector
* @lua NA
*/
void schedule(SEL_SCHEDULE selector); /**
* Unschedules a custom selector.
* @see schedule(SEL_SCHEDULE, float, unsigned int, float)
*
* @param selector A function wrapped as a selector
* @lua NA
*/
void unschedule(SEL_SCHEDULE selector); /**
* Unschedule all scheduled selectors: custom selectors, and the 'update' selector.
* Actions are not affected by this method.
*/
void unscheduleAllSelectors(void); /**
* Resumes all scheduled selectors and actions.
* This method is called internally by onEnter
* @js NA
* @lua NA
*/
void resumeSchedulerAndActions(void);
/**
* Pauses all scheduled selectors and actions.
* This method is called internally by onExit
* @js NA
* @lua NA
*/
void pauseSchedulerAndActions(void); /*
* Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live"
*/
virtual void update(float delta); /// @} end of Scheduler and Timer /// @{
/// @name Transformations /**
* Performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes.
*/
void transform(void);
/**
* Performs OpenGL view-matrix transformation of it's ancestors.
* Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO)
* It's necessary to transform the ancestors again.
*/
void transformAncestors(void);
/**
* Calls children's updateTransform() method recursively.
*
* This method is moved from CCSprite, so it's no longer specific to CCSprite.
* As the result, you apply CCSpriteBatchNode's optimization on your customed CCNode.
* e.g., batchNode->addChild(myCustomNode), while you can only addChild(sprite) before.
*/
virtual void updateTransform(void); /**
* Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
* The matrix is in Pixels.
*/
virtual CCAffineTransform nodeToParentTransform(void); /**
* Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates.
* The matrix is in Pixels.
*/
virtual CCAffineTransform parentToNodeTransform(void); /**
* Returns the world affine transform matrix. The matrix is in Pixels.
*/
virtual CCAffineTransform nodeToWorldTransform(void); /**
* Returns the inverse world affine transform matrix. The matrix is in Pixels.
*/
virtual CCAffineTransform worldToNodeTransform(void); /// @} end of Transformations /// @{
/// @name Coordinate Converters /**
* Converts a Point to node (local) space coordinates. The result is in Points.
*/
CCPoint convertToNodeSpace(const CCPoint& worldPoint); /**
* Converts a Point to world space coordinates. The result is in Points.
*/
CCPoint convertToWorldSpace(const CCPoint& nodePoint); /**
* Converts a Point to node (local) space coordinates. The result is in Points.
* treating the returned/received node point as anchor relative.
*/
CCPoint convertToNodeSpaceAR(const CCPoint& worldPoint); /**
* Converts a local Point to world space coordinates.The result is in Points.
* treating the returned/received node point as anchor relative.
*/
CCPoint convertToWorldSpaceAR(const CCPoint& nodePoint); /**
* convenience methods which take a CCTouch instead of CCPoint
*/
CCPoint convertTouchToNodeSpace(CCTouch * touch); /**
* converts a CCTouch (world coordinates) into a local coordinate. This method is AR (Anchor Relative).
*/
CCPoint convertTouchToNodeSpaceAR(CCTouch * touch); /**
* Sets the additional transform.
*
* @note The additional transform will be concatenated at the end of nodeToParentTransform.
* It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn't).
* @code
// create a batchNode
CCSpriteBatchNode* batch= CCSpriteBatchNode::create("Icon-114.png");
this->addChild(batch); // create two sprites, spriteA will be added to batchNode, they are using different textures.
CCSprite* spriteA = CCSprite::createWithTexture(batch->getTexture());
CCSprite* spriteB = CCSprite::create("Icon-72.png"); batch->addChild(spriteA); // We can't make spriteB as spriteA's child since they use different textures. So just add it to layer.
// But we want to simulate `parent-child` relationship for these two node.
this->addChild(spriteB); //position
spriteA->setPosition(ccp(200, 200)); // Gets the spriteA's transform.
CCAffineTransform t = spriteA->nodeToParentTransform(); // Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t); //scale
spriteA->setScale(2); // Gets the spriteA's transform.
t = spriteA->nodeToParentTransform(); // Sets the additional transform to spriteB, spriteB's scale will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t); //rotation
spriteA->setRotation(20); // Gets the spriteA's transform.
t = spriteA->nodeToParentTransform(); // Sets the additional transform to spriteB, spriteB's rotation will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t);
* @endcode
*/
void setAdditionalTransform(const CCAffineTransform& additionalTransform); /// @} end of Coordinate Converters /// @{
/// @name component functions
/**
* gets a component by its name
*/
CCComponent* getComponent(const char *pName) const; /**
* adds a component
*/
virtual bool addComponent(CCComponent *pComponent); /**
* removes a component by its name
*/
virtual bool removeComponent(const char *pName); /**
* removes all components
*/
virtual void removeAllComponents();
/// @} end of component functions private:
/// lazy allocs
void childrenAlloc(void); /// helper that reorder a child
void insertChild(CCNode* child, int z); /// Removes a child, call child->onExit(), do cleanup, remove it from children array.
void detachChild(CCNode *child, bool doCleanup); /** Convert cocos2d coordinates to UI windows coordinate.
* @js NA
* @lua NA
*/
CCPoint convertToWindowSpace(const CCPoint& nodePoint); protected:
float m_fRotationX; ///< rotation angle on x-axis
float m_fRotationY; ///< rotation angle on y-axis float m_fScaleX; ///< scaling factor on x-axis
float m_fScaleY; ///< scaling factor on y-axis float m_fVertexZ; ///< OpenGL real Z vertex CCPoint m_obPosition; ///< position of the node float m_fSkewX; ///< skew angle on x-axis
float m_fSkewY; ///< skew angle on y-axis CCPoint m_obAnchorPointInPoints; ///< anchor point in points
CCPoint m_obAnchorPoint; ///< anchor point normalized (NOT in points) CCSize m_obContentSize; ///< untransformed size of the node CCAffineTransform m_sAdditionalTransform; ///< transform
CCAffineTransform m_sTransform; ///< transform
CCAffineTransform m_sInverse; ///< transform CCCamera *m_pCamera; ///< a camera CCGridBase *m_pGrid; ///< a grid int m_nZOrder; ///< z-order value that affects the draw order CCArray *m_pChildren; ///< array of children nodes
CCNode *m_pParent; ///< weak reference to parent node int m_nTag; ///< a tag. Can be any number you assigned just to identify this node void *m_pUserData; ///< A user assingned void pointer, Can be point to any cpp object
CCObject *m_pUserObject; ///< A user assigned CCObject CCGLProgram *m_pShaderProgram; ///< OpenGL shader ccGLServerState m_eGLServerState; ///< OpenGL servier side state unsigned int m_uOrderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder CCScheduler *m_pScheduler; ///< scheduler used to schedule timers and updates CCActionManager *m_pActionManager; ///< a pointer to ActionManager singleton, which is used to handle all the actions bool m_bRunning; ///< is running bool m_bTransformDirty; ///< transform dirty flag
bool m_bInverseDirty; ///< transform dirty flag
bool m_bAdditionalTransformDirty; ///< The flag to check whether the additional transform is dirty
bool m_bVisible; ///< is this node visible bool m_bIgnoreAnchorPointForPosition; ///< true if the Anchor Point will be (0,0) when you position the CCNode, false otherwise.
///< Used by CCLayer and CCScene. bool m_bReorderChildDirty; ///< children order dirty flag int m_nScriptHandler; ///< script handler for onEnter() & onExit(), used in Javascript binding and Lua binding.
int m_nUpdateScriptHandler; ///< script handler for update() callback per frame, which is invoked from lua & javascript.
ccScriptType m_eScriptType; ///< type of script binding, lua or javascript CCComponentContainer *m_pComponentContainer; ///< Dictionary of components }; 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 interval,unsigned int  repeat,

float delay)

添加一个schedule定时器,其中selector
参数为定时器的事件函数,interval参
数为定时器的时间间隔,repeat参数为定
时事件触发一次后还会再次触发
的次数(默认值为kCCRepeatForever,
表示触发无穷多次),delay为第一次触
发事件前的延时。此处时间都以秒为单位

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*型的参数。