欢迎转载:http://blog.csdn.net/fylz1125/article/details/8522523
这个CCNode是个很重要的基类,没有理由不把它搞一搞。
首先看下类结构图:
它几乎是所有类的基类,官方注释如下:
CCNode是主要元素。任何一个能被绘制或者包含能被绘制的东西都是一个CCNode。
最常用的CCNode有:CCScene,cclayer,CCSprite,Ccmenu.
1.他们能够容纳别的CCNode节点,别如能addChild,getChildByTag,removeChild 。
2.他们能定期的调度回调函数,比如能schedule,unschedule等。
3.他们能执行动作,比如runAciton,stopAction等。
一些节点能给自己或他们的子几点提供一些额外额功能。
继承一个CCNode节点通常意味着如下几条:
1.重写init()函数来初始化资源和回调
2.创建回调函数来处理时间片
3.重写draw来绘制节点
另外,一个CCNode是一个看不见对象,他没有纹理。每个节点都有一个Camera,默认指向节点的中心点。
看下这个类
- classCC_DLLCCNode:publicCCObject
- {
- protected:
- //rotationangle
- floatm_fRotationX,m_fRotationY;
- //scalingfactors缩放因子
- floatm_fScaleX,m_fScaleY;
- //openglrealZvertex
- floatm_fVertexZ;
- //positionofthenode
- CCPointm_obPosition;
- //skewangles
- floatm_fSkewX,m_fSkewY;
- //anchorpointinpoints锚点(points形式)
- CCPointm_obAnchorPointInPoints;
- //anchorpointnormalized(notinpoints)锚点(比例形式)
- CCPointm_obAnchorPoint;
- //untransformedsizeofthenode
- CCSizem_obContentSize;
- //transform
- CCAffineTransformm_sTransform,m_sInverse;
- //aCamera
- CCCamera*m_pCamera;
- //aGrid
- CCGridBase*m_pGrid;
- //z-ordervalue
- intm_nZOrder;
- //arrayofchildren
- CCArray*m_pChildren;//关键数组,存子节点
- //weakreftoparent
- CCNode*m_pParent;//父节点
- //atag.anynumberyouwanttoassigntothenode
- intm_nTag;//tag标记
- //userdatafield
- void*m_pUserData;
- CCObject*m_pUserObject;
- //Shader
- CCGLProgram*m_pShaderProgram;//着色器
- //Serversidestate
- ccGLServerStatem_eGLServerState;
- //usedtopreservesequencewhilesortingchildrenwiththesamezOrder
- unsignedintm_uOrderOfArrival;
- //schedulerusedtoscheduletimersandupdates
- CCScheduler*m_pScheduler;//调度器,调度定时器执行一些函数
- //ActionManagerusedtohandlealltheactions
- CCActionManager*m_pActionManager;//动作管理器,处理所有动作
- //Isrunning
- boolm_bRunning;//状态标志
- boolm_bTransformDirty;
- boolm_bInverseDirty;
- //isvisible
- boolm_bVisible;//是否可见
- //Iftrue,theAnchorPointwillbe(0,0)whenyoupositiontheCCNode.
- //UsedbycclayerandCCScene
- boolm_bIgnoreAnchorPointForPosition;
- boolm_bReorderChildDirty;
- //Propertiesforscript
- //scripthandler
- intm_nScriptHandler;
- intm_nUpdateScriptHandler;
- //scripttype,luaorjavascript
- ccScriptTypem_eScriptType;
- public:
- //getter&setter
- /**Thezorderofthenoderelativetoit's"brothers":childrenofthesameparent*/
- virtualintgetZOrder();//取得z坐标,相对于同一父节点
- virtualvoidsetZOrder(intnZOrder);
- /**TherealopenGLZvertex.
- DifferencesbetweenopenGLZvertexandcocos2dZorder:
- -OpenGLZmodifiestheZvertex,andnottheZorderintherelationbetweenparent-children
- -OpenGLZmightrequiretoset2Dprojection
- -cocos2dZorderworksOKifallthenodesusesthesameopenGLZvertex.eg:vertexZ=0
- @warning:Useitatyourownrisksinceitmightbreakthecocos2dparent-childrenzorder
- @sincev0.8
- */
- virtualfloatgetVertexZ();
- virtualvoidsetVertexZ(floatfVertexZ);
- /**Thescalefactorofthenode.1.0isthedefaultscalefactor.ItonlymodifiestheXscalefactor.*/
- floatgetScaleX();
- virtualvoidsetScaleX(floatfScaleX);
- /**Thescalefactorofthenode.1.0isthedefaultscalefactor.Itonlymodifiestheyscalefactor.*/
- floatgetScaleY();
- virtualvoidsetScaleY(floatfScaleY);
- /**Position(x,y)ofthenodeinopenGLcoordinates.(0,0)istheleft-bottomcorner.*/
- virtualCCPointgetPosition();
- virtualvoidsetPosition(constCCPoint&position);
- /**TheXskewangleofthenodeindegrees.
- ThisangledescribesthesheardistortionintheXdirection.
- Thus,itistheanglebetweentheyaxisandtheleftedgeoftheshape
- ThedefaultskewXangleis0.PositivevaluesdistortthenodeinaCWdirection.
- floatgetSkewX();
- virtualvoidsetSkewX(floatfSkewX);
- /**Theyskewangleofthenodeindegrees.
- Thisangledescribesthesheardistortionintheydirection.
- ottomedgeoftheshape
- ThedefaultskewYangleis0.Positivevaluesdistortthenodeinaccwdirection.
- floatgetSkewY();
- virtualvoidsetSkewY(floatfSkewY);
- virtualCCArray*getChildren();
- /**ACCCameraobjectthatletsyoumovethenodeusingagluLookAt
- */
- virtualCCCamera*getCamera();
- /**ACCGridobjectthatisusedwhenapplyingeffects*/
- virtualCCGridBase*getGrid();
- virtualvoidsetGrid(CCGridBase*pGrid);
- /**Atagusedtoidentifythenodeeasily*/
- intgetTag();
- virtualvoidsetTag(intnTag);
- /**Acustomuserdatapointer*/
- virtualvoid*getUserData();
- virtualvoidsetUserData(void*pUserData);
- /**SimilartouserData,butinsteadofholdingavoid*itholdsanid*/
- virtualCCObject*getUserObject();
- virtualvoidsetUserObject(CCObject*pUserObject);//retain
- /**ShaderProgram
- @sincev2.0
- virtualCCGLProgram*getShaderProgram();
- virtualvoidsetShaderProgram(CCGLProgram*pShaderProgram);
- /**usedinternallyforzOrdersorting,don'tchangethismanually*/
- virtualunsignedintgetorderOfArrival();
- virtualvoidsetorderOfArrival(unsignedintuOrderOfArrival);
- /**GLserversidestate
- virtualccGLServerStategetGLServerState();
- virtualvoidsetGLServerState(ccGLServerStateglServerState);
- /**CCActionManagerusedbyalltheactions.
- IMPORTANT:IfyousetanewCCActionManager,thenprevIoUslycreatedactionsaregoingtoberemoved.
- @sincev2.0
- virtualCCActionManager*getActionManager();
- virtualvoidsetActionManager(CCActionManager*pActionManager);
- /**CCSchedulerusedtoscheduleall"updates"andtimers.
- IMPORTANT:IfyousetanewCCScheduler,thenprevIoUslycreatedtimers/updatearegoingtoberemoved.
- virtualCCScheduler*getScheduler();
- virtualvoidsetScheduler(CCScheduler*pScheduler);
- /**Aweakreferencetotheparent*/
- virtualCCNode*getParent();
- virtualvoidsetParent(CCNode*pParent);
- /**anchorPointisthepoinTaroundwhichalltransformationsandpositioningmanipulationstakeplace.
- It'slikeapininthenodewhereitis"attached"toitsparent.
- TheanchorPointisnormalized,likeapercentage.(0,0)meansthebottom-leftcornerand(1,1)meansthetop-rightcorner.
- Butyoucanusevalueshigherthan(1,1)andlowerthan(0,0)too.
- ThedefaultanchorPointis(0.5,0.5),soitstartsinthecenterofthenode.
- virtualCCPointgetAnchorPoint();
- virtualvoidsetAnchorPoint(constCCPoint&anchorPoint);
- /**TheanchorPointinabsolutepixels.
- Sincev0.8youcanonlyreadit.Ifyouwishtomodifyit,useanchorPointinstead
- virtualCCPointgetAnchorPointInPoints();
- /**Theuntransformedsizeofthenode.
- ThecontentSizeremainsthesamenomatterthenodeisscaledorrotated.
- Allnodeshasasize.LayerandScenehasthesamesizeofthescreen.
- @sincev0.8
- virtualCCSizegetContentSize();
- virtualvoidsetContentSize(constCCSize&contentSize);
- boolisVisible();
- virtualvoidsetVisible(boolvisible);
- /**Getthescalefactorofthenode.
- @warning:Assertwhenm_fScaleX!=m_fScaleY.
- floatgetScale();
- /**Thescalefactorofthenode.1.0isthedefaultscalefactor.ItmodifiestheXandYscaleatthesametime.*/
- virtualvoidsetScale(floatscale);
- /**Therotation(angle)ofthenodeindegrees.0isthedefaultrotationangle.PositivevaluesrotatenodeCW.*/
- floatgetRotation();
- virtualvoidsetRotation(floatfRotation);
- /**Therotation(angle)ofthenodeindegrees.0isthedefaultrotationangle.PositivevaluesrotatenodeCW.ItonlymodifiestheXrotationperformingahorizontalrotationalskew.*/
- floatgetRotationX();
- virtualvoidsetRotationX(floatfRotaionX);
- /**Therotation(angle)ofthenodeindegrees.0isthedefaultrotationangle.PositivevaluesrotatenodeCW.Itonlymodifiestheyrotationperformingaverticalrotationalskew.*/
- floatgetRotationY();
- virtualvoidsetRotationY(floatfRotationY);
- /**whetherornotthenodeisrunning*/
- boolisRunning();
- boolisIgnoreAnchorPointForPosition();
- virtualvoidignoreAnchorPointForPosition(boolisIgnoreAnchorPointForPosition);
- /**Getchildrencount*/
- unsignedintgetChildrenCount(void);
- void_setZOrder(intz);
- /**GetscripthandlerforonEnter/onExitevent.*/
- inlineintgetScriptHandler(){returnm_nScriptHandler;};
- /**get/setPositionforLua(passnumberfasterthanCCPointobject)
- luacode:
- localpos=node:getPositionLua()--returnCCPointobjectfromC++
- localx,y=node:getPosition()--returnx,yvaluesfromC++
- localx=node:getPositionX()
- localy=node:getPositionY()
- node:setPosition(x,y)--passx,yvaluestoC++
- node:setPositionX(x)
- node:setPositionY(y)
- constCCPoint&getPositionLua(void);
- voidgetPosition(float*x,float*y);
- floatgetPositionX(void);
- floatgetPositionY(void);
- voidsetPositionX(floatx);
- voidsetPositionY(floaty);
- voidsetPosition(floatx,87); font-weight:bold; background-color:inherit">floaty);
- public:
- CCNode(void);
- virtual~CCNode(void);
- constchar*description(void);
- /**allocatesandinitializesanode.
- Thenodewillbecreatedas"autorelease".
- staticCCNode*create(void);//自动释放对象构造器
- //scenemanagement
- /**callbackthatiscalledeverytimetheCCNodeentersthe'stage'.
- IftheCCNodeentersthe'stage'withatransition,thiscallbackiscalledwhenthetransitionstarts.
- DuringonEnteryoucan'ta"sister/brother"node.
- virtualvoidonEnter();//回调。如果节点进入时又过渡,那么在过渡开始时调度
- /**callbackthatiscalledwhentheCCNodeentersinthe'stage'.
- virtualvoidonEnterTransitionDidFinish();//回调,当过渡结束时调用
- /**callbackthatiscalledeverytimetheCCNodeleavesthe'stage'.
- IftheCCNodeleavesthe'stage'withatransition,0); background-color:inherit">DuringonExityoucan'taccessasiblingnode.
- virtualvoidonExit();//回调,节点离开时,如果有过渡,则在过渡结束时调用
- virtualvoidonExitTransitionDidStart();//回调,离开时,在过渡开始时调用
- /**RegisteronEnter/onExithandlerscriptfunction
- ScripthandlerautounregisterafteronEnter().
- virtualvoidregisterScriptHandler(intnHandler);
- virtualvoidunregisterScriptHandler(void);
- //composition:ADD
- /**Addsachildtothecontainerwithz-orderas0.
- Ifthechildisaddedtoa'running'node,then'onEnter'and'onEnterTransitionDidFinish'willbecalledimmediately.
- @sincev0.7.1
- virtualvoidaddChild(CCNode*child);//添加一个子节点,默认z坐标为0.如果一个子节点被添加到一个正在运行的节点,那么这个子节点的onEnter和onEnterTransitionDidFinish会被立即调用
- /**Addsachildtothecontainerwithaz-order
- virtualvoidaddChild(CCNode*child,87); font-weight:bold; background-color:inherit">intzOrder);//添加一个子节点,设置z坐标
- /**Addsachildtothecontainerwithzorderandtag
- intzOrder,87); font-weight:bold; background-color:inherit">inttag);//添加子节点,设置z坐标和tag标记
- //composition:REMOVE
- /**Removeitselffromitsparentnodeforcingacleanup.
- Ifthenodeorphan,thennothinghappens.
- @sincev2.1
- virtualvoidremoveFromParent();//从父节点删除自己,如果没有父节点则什么都不干
- /**Removeitselffromitsparentnode.Ifcleanupistrue,thenalsoremoveallactionsandcallbacks.
- @sincev0.99.3
- virtualvoidremoveFromParentAndCleanup(boolcleanup);//从父节点删除自己,如果cleanup标记为true,则删除其所有动作和回调函数
- /**Removesachildfromthecontainerforcingacleanup
- @sincev2.1
- virtualvoidremoveChild(CCNode*child);//删除一个子节点,强制cleanup为true
- /**Removesachildfromthecontainer.Itwillalsocleanupallrunningactionsdependingonthecleanupparameter.
- virtualvoidremoveChild(CCNode*child,87); font-weight:bold; background-color:inherit">boolcleanup);
- /**Removesachildfromthecontainerbytagvalueforcingacleanup.
- virtualvoidremoveChildByTag(inttag);
- /**Removesachildfromthecontainerbytagvalue.Itwillalsocleanupallrunningactionsdependingonthecleanupparameter
- virtualvoidremoveChildByTag(inttag,0); background-color:inherit">/**Removesallchildrenfromthecontainerforcingacleanup.
- virtualvoidremoveAllChildren();//删除所有子节点及其动作和回调,即cleanup强置true
- /**Removesallchildrenfromthecontaineranddoacleanupallrunningactionsdependingonthecleanupparameter.
- virtualvoidremoveAllChildrenWithCleanup(//composition:GET
- /**Getsachildfromthecontainergivenitstag
- @returnreturnsaCCNodeobject
- @sincev0.7.1
- CCNode*getChildByTag(/**Reordersachildaccordingtoanewzvalue.
- *ThechildMUSTbealreadyadded.
- virtualvoidreorderChild(CCNode*child,87); font-weight:bold; background-color:inherit">intzOrder);
- /**performanceimprovement,Sortthechildrenarrayoncebeforedrawing,insteadofeverytimewhenachildisaddedorreordered
- don'tcallthismanuallyunlessachildaddedneedstoberemovedinthesameframe*/
- virtualvoidsortAllChildren();
- /**Stopsallrunningactionsandschedulers
- virtualvoidcleanup(void);//停止所有动作和任务调度
- //draw
- /**Overridethismethodtodrawyourownnode.
- ThefollowingGLstateswillbeenabledbydefault:
- -glEnableClientState(GL_VERTEX_ARRAY);
- -glEnableClientState(GL_COLOR_ARRAY);
- -glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- -glEnable(GL_TEXTURE_2D);
- ANDYOUSHOULDNOTdisABLETHEMAFTERDRAWINGYOURNODE
- ButifyouenableanyotherGLstate,youshoulddisableitafterdrawingyournode.
- virtualvoiddraw(void);//画自己
- /**recursivemethodthatvisititschildrenanddrawthem*/
- virtualvoidvisit(void);//递归访问子节点并绘制它们
- //transformations
- //MARMALADEADDEDTHIS...soITISNOLONGERSPECIFICTOCCSprite
- /**updatesthequadaccordingthetherotation,position,scalevalues.*/
- virtualvoidupdateTransform(void);
- /**performsOpenGLview-matrixtransformationbasedonposition,scale,rotationandotherattributes.*/
- voidtransform(void);
- /**performsOpenGLview-matrixtransformationofit'sancestors.
- Generallytheancestorsarealreadytransformed,butincertaincases(eg:attachingaFBO)
- it'snecessarytotransformtheancestorsagain.
- @sincev0.7.2
- voidtransformAncestors(void);
- /**returnsa"local"axisalignedboundingBoxofthenode.
- ThereturnedBoxisrelativeonlytoitsparent.
- @sincev0.8.2
- CCRectboundingBox(void);//返回节点的边框矩形区域,相对于其父节点
- //actions
- /**Executesanaction,andreturnstheactionthatisexecuted.
- Thenodebecomestheaction'starget.
- @warningStartingfromv0.8actionsdon'tretaintheirtargetanymore.
- @returnAnActionpointer
- CCAction*runAction(CCAction*action);//执行一个动作。执行动作的节点将变成动作的target
- /**Removesallactionsfromtherunningactionlist*/
- voidstopAllActions(void);
- /**Removesanactionfromtherunningactionlist*/
- voidstopAction(CCAction*action);
- /**Removesanactionfromtherunningactionlistgivenitstag
- voidstopActionByTag(/**Getsanactionfromtherunningactionlistgivenitstag
- @returntheActionthewiththegiventag
- CCAction*getActionByTag(/**Returnsthenumbersofactionsthatarerunningplustheonesthatarescheduletorun(actionsinactionsToAddandactionsarrays).
- *Composableactionsarecountedas1action.Example:
- *Ifyouarerunning1Sequenceof7actions,itwillreturn1.
- *Ifyouarerunning7Sequencesof2actions,itwillreturn7.
- intnumberOfRunningActions(void);
- //timers
- /**checkwhetheraselectorisscheduled.*/
- boolisScheduled(SEL_SCHEDULEselector);//检测一个选择器是否被调用
- /**schedulesthe"update"method.Itwillusetheordernumber0.Thismethodwillbecalledeveryframe.
- Scheduledmethodswithalowerordervaluewillbecalledbeforetheonesthathaveahigherordervalue.
- Onlyone"update"methodCouldbescheduledpernode.
- voidscheduleUpdate(void);//采用0优先级调度update函数,这个函数每一帧都会被执行,优先级数字越小,权重越高,也就越优先调用。每个节点只能有一个update被调度。
- /**schedulesthe"update"selectorwithacustompriority.Thisselectorwillbecalledeveryframe.
- Scheduledselectorswithalowerprioritywillbecalledbeforetheonesthathaveahighervalue.
- Onlyone"update"selectorCouldbescheduledpernode(Youcan'thave2'update'selectors).
- voidscheduleUpdateWithPriority(intpriority);//用一个优先级调度update函数,每一帧都调用
- /*unschedulesthe"update"method.
- voidunscheduleUpdate(void);//停止调度update函数
- /**schedulesaselector.
- Thescheduledselectorwillbetickedeveryframe
- voidschedule(SEL_SCHEDULEselector);//选择器selector每一帧都被调一次
- /**schedulesacustomselectorwithanintervaltimeinseconds.
- Iftimeis0itwillbetickedeveryframe.
- Iftimeis0,itisrecommendedtouse'scheduleUpdate'instead.
- Iftheselectorisalreadyscheduled,thentheintervalparameter
- willbeupdatedwithoutschedulingitagain.
- voidschedule(SEL_SCHEDULEselector,87); font-weight:bold; background-color:inherit">floatinterval);//自定义时间间隔调度选择器selector,比如每秒一次
- /**
- repeatwillexecutetheactionrepeat+1times,foracontinuesactionusekCCRepeatForever
- delayistheamountoftimetheactionwillwaitbeforeexecution
- floatinterval,unsignedintrepeat,87); font-weight:bold; background-color:inherit">floatdelay);
- Schedulesaselectorthatrunsonlyonce,withadelayof0orlarger
- voidscheduleOnce(SEL_SCHEDULEselector,87); font-weight:bold; background-color:inherit">floatdelay);//以一个延迟时间调度回调selector,仅调用一次
- /**unschedulesacustomselector.*/
- voidunschedule(SEL_SCHEDULEselector);//停止调度自定义的选择器
- /**unscheduleallscheduledselectors:customselectors,andthe'update'selector.
- Actionsarenotaffectedbythismethod.
- @sincev0.99.3
- voidunscheduleAllSelectors(void);//停止调用所有选择器,包括自定义的和内置的update
- /**resumesallscheduledselectorsandactions.
- CalledinternallybyonEnter
- voidresumeSchedulerAndActions(void);
- /**pausesallscheduledselectorsandactions.
- CalledinternallybyonExit
- voidpauseSchedulerAndActions(void);
- /*Updatewillbecalledautomaticallyeveryframeif"scheduleUpdate"iscalled,andthenodeis"live"
- virtualvoidupdate(floatfDelta);//内置的选择器,如果调用了scheduleUpdate,那么这个选择器每一帧都会被调用
- //transformationmethods
- /**Returnsthematrixthattransformthenode's(local)spacecoordinatesintotheparent'sspacecoordinates.
- ThematrixisinPixels.
- virtualCCAffineTransformnodetoParentTransform(void);
- /**Returnsthematrixthattransformparent'sspacecoordinatestothenode's(local)spacecoordinates.
- virtualCCAffineTransformparentToNodeTransform(void);
- /**Returnstheworldaffinetransformmatrix.ThematrixisinPixels.
- virtualCCAffineTransformnodetoWorldTransform(void);
- /**Returnstheinverseworldaffinetransformmatrix.ThematrixisinPixels.
- virtualCCAffineTransformworldToNodeTransform(void);
- /**ConvertsaPointtonode(local)spacecoordinates.TheresultisinPoints.
- CCPointconvertToNodeSpace(constCCPoint&worldPoint);//将世界坐标系的点转换为节点的本地坐标系的点
- /**ConvertsaPointtoworldspacecoordinates.TheresultisinPoints.
- CCPointconvertToWorldspace(constCCPoint&nodePoint);//将节点的本地坐标系的点转换为世界坐标系的点
- treatingthereturned/receivednodepointasanchorrelative.
- CCPointconvertToNodeSpaceAR(constCCPoint&worldPoint);//将世界坐标系的点转换为基于锚点的节点本地坐标系的点
- /**ConvertsalocalPointtoworldspacecoordinates.TheresultisinPoints.
- treatingthereturned/receivednodepointasanchorrelative.
- CCPointconvertToWorldspaceAR(constCCPoint&nodePoint);//将基于锚点的节点的本地坐标系的点转换为世界坐标系的点
- /**conveniencemethodswhichtakeaCCTouchinsteadofCCPoint
- CCPointconvertTouchToNodeSpace(CCTouch*touch);//将一个屏幕坐标系的touch转换为节点的本地坐标系的点
- /**convertsaCCTouch(worldcoordinates)intoalocalcoordinate.ThismethodisAR(AnchorRelative).
- CCPointconvertTouchToNodeSpaceAR(CCTouch*touch);
- /**Schedulesforscript.*/
- voidscheduleUpdateWithPriorityLua(intnHandler,87); font-weight:bold; background-color:inherit">intpriority);
其中有有些较重要的成员变量和函数,做了注释,后面陆续写写。