本文隶属于专题系列: cocos2dx基础篇

目录

  • ----------------------------------------

  • 入口类main.cpp

  • 主要控制类AppDelegate.cpp

  • ----------------------------------------

  • 对象类CCObject

  • 节点类CCNode

  • ----------------------------------------

  • 导演类CCDirector

  • 场景类CCScene

  • 图层类CCLayer

  • 精灵类CCSprite

  • ----------------------------------------

  • 坐标类CCPoint

  • 尺寸大小类CCSize

  • 矩形类CCRect

  • ----------------------------------------

  • 数组类CCArray

  • ----------------------------------------

    PS:这里只对上述类中的相关函数进行讲解,因为函数太多,使用方法还是要通过自己在开发游戏项目的过程中慢慢摸索练习。

  • 入口类main.cpp

    这是应用程序的入口类,用于创建cocos2dx的AppDelegate实例、窗口大小、以及运行程序。

    主要代码如下:

    // create the application instance
    AppDelegate app; //创建一个主控制类AppDelegate
    CCEGLView* eglView = CCEGLView::sharedOpenGLView(); //使用OpenGL进行图形渲染
    eglView->setViewName("hello");                      //程序窗口标题
    eglView->setFrameSize(480, 320);                    //程序窗口分辨率大小
    return CCApplication::sharedApplication()->run();
  • 主要控制类AppDelegate.cpp

    这是游戏程序的入口,主要用于游戏程序的逻辑初始化,并创建运行程序的入口界面(即第一个游戏界面场景)。

    里面有三个方法:

        applicationDidFinishLaunching();  //逻辑初始化
        applicationDidEnterBackground();  //切换到后台
        applicationWillEnterForeground(); //切换到前台

    源码分析:

bool AppDelegate::applicationDidFinishLaunching() { //逻辑初始化
	//初始化一个导演, 只能有一个导演
    CCDirector* pDirector = CCDirector::sharedDirector();
	//使用OpenGLView
	pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
	//屏幕适配,设置游戏设计的分辨率
	CCEGLView::sharedOpenGLView()->setDesignResolutionSize(480,320,kResolutionShowAll);
    //开启状态显示, 帧数,精灵数等
    pDirector->setDisplayStats(false);
    //刷新频率,每秒60帧。
    pDirector->setAnimationInterval(1.0 / 60);
    //创建一个场景Hello,这是游戏程序的第一个界面
    CCScene *pScene = Hello::scene();
    //运行
    pDirector->runWithScene(pScene);
    return true;
}
// 切换到后台
void AppDelegate::applicationDidEnterBackground() { 
	//暂停游戏
	CCDirector::sharedDirector()->stopAnimation();
    // 暂停音乐
    SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// 切换到前台
void AppDelegate::applicationWillEnterForeground() { 
	//游戏恢复
	CCDirector::sharedDirector()->startAnimation();
    //音乐恢复
    SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}

    讲到这里,大家可能会感到疑惑。为什么会设置了两次分辨率大小呢?

        eglView->setFrameSize(480, 320);

        CCEGLView::sharedOpenGLView()->setDesignResolutionSize(480,320,kResolutionShowAll);

    朋友们,这两个的意义是不一样滴。

    setDesignResolutionSize 是设置了我们游戏设计时候的分辨率,即想要适配的宽480高320的屏幕比例。也就是说设计者初衷的游戏分辨率屏幕大小。但是对于每个用户来说,他们使用的设备不一定是(480,320)的,比如手机有大有小。而后面的 kResolutionShowAll 参数意思是按照原比例(480/320)进行放缩以适配设备的实际屏幕。

    eglView->setFrameSize(480, 320) 则是设置我们预想设备的屏幕大小,也就是应用程序窗口的大小。

    以下贴了几张对比图,加深理解。

    1、这是原图片大小,窗口大小为480 * 320。

wKiom1PrKH3CcRIOAAD_nAYof-Q636.jpg

    2、若设置窗口大小为setFrameSize(960, 640),而不设置设计分辨率放缩比例kResolutionShowAll 的情况下,图片不放缩,原图还是480 * 320。

wKioL1PrKZbAgMrIAAFr7Y9wj5U764.jpg

    3、设置了 kResolutionShowAll 之后,图片放缩到适配整个屏幕960 * 640 了。

wKiom1PrKH2BVTStAALbxOSia9g185.jpg

  • 对象类CCObject

    这个类是所有类的开始,主要包含了节点的内存管理机制,内存的释放、保留、复制等操作。

    有兴趣的可以自己去找资料学一下内存管理机制。

    主要函数如下:

void release(void);                                   //释放资源
void retain(void);                                    //保留资源,不被回收
CCObject* autorelease(void);                          //设置实例对象的释放由内存管理器进行管理,实现自动释放
CCObject* copy(void);                                 //拷贝对象
bool isSingleReference(void) const;                   //判断对象是否只有一个使用者
unsigned int retainCount(void) const;                 //返回内存计数器,即对象的使用者个数
virtual bool isEqual(const CCObject* pObject);        //判断是否与pObject对象相同
virtual void update(float dt) {CC_UNUSED_PARAM(dt);}; //更新函数,与scheduleUpdate()对应
friend class CCAutoreleasePool;                       //友元类,管理对象的内存使用情况
//
  • 节点类CCNode

    参考博客:http://blog.csdn.net/qiurisuixiang/article/details/8763260

    CCNode类是绝大部分类的父类(并不是所有的类,例如CCDirector类是直接继承CCObject类的),如CCScene、CCLayer、CCSprite以及精灵集合CCSpriteBatchNode等等等等的父类都是CCNode。

    CCNode类包含了一些基本的属性、节点相关、Action动作的执行、以及定时器等相关的操作。

    当然CCNode也有父类,其父类为CCObject。

    继承关系如下:

wKiom1PsSwjx7-B9AAAwExS1jxg442.jpg

    主要函数如下:

/**
 *    属性相关函数
 *    Visible , ContentSize , Position , AnchorPoint , 
 *    ZOrder , Scale , Skew , Rotation
 */
//设置节点是否可见.
virtual void setVisible(bool visible);
virtual bool isVisible();
//设置节点的尺寸大小.即节点的容器大小.
virtual void setContentSize(const CCSize& contentSize);
virtual const CCSize& getContentSize() const;
//设置节点的坐标(x,y).在OpenGL中的坐标
virtual void setPosition(const CCPoint &position); //传参为坐标类CCPoint
virtual const CCPoint& getPosition();
virtual void setPosition(float x, float y);
virtual void getPosition(float* x, float* y);
virtual void  setPositionX(float x);
virtual float getPositionX(void);
virtual void  setPositionY(float y);
virtual float getPositionY(void);
//设置节点的锚点.
//锚点就像一枚图钉,将图片钉在屏幕上.而锚点就是图片的坐标.
//当然图钉可以钉在图片的左下角,右上角,或者中心都可以.
//一般由CCNode继承的子类大多锚点都在中心,也有些是在左下角.
virtual void setAnchorPoint(const CCPoint& anchorPoint);
virtual const CCPoint& getAnchorPoint();
virtual const CCPoint& getAnchorPointInPoints();
//设置节点的Z轴.
//当有多个节点在Z轴显示时,引擎会根据它们Z轴的大小决定绘制顺序,Z轴大的会遮盖Z轴小的
virtual void setZOrder(int zOrder);
virtual int getZOrder();
//设置节点的放缩比例.对X轴或Y轴进行放缩
//例如一张图片. 放缩它的宽X,和高Y
virtual void setScaleX(float fScaleX);              //放缩宽X
virtual float getScaleX();
virtual void setScaleY(float fScaleY);              //放缩高Y
virtual float getScaleY();
virtual void setScale(float scale);                 //同时放缩X与Y
virtual float getScale();
virtual void setScale(float fScaleX,float fScaleY); //X放缩fScaleX倍,Y放缩fScaleY倍
//设置节点的倾斜角度.与平面的倾斜角度
//如一张图片. X轴倾斜fSkewX角度,Y轴倾斜fSkewY角度
virtual void setSkewX(float fSkewX);
virtual float getSkewX();
virtual void setSkewY(float fSkewY);
virtual float getSkewY();
//设置节点旋转角度.
virtual void setRotation(float fRotation);
virtual float getRotation();
virtual void setRotationX(float fRotaionX);
virtual float getRotationX();
virtual void setRotationY(float fRotationY);
virtual float getRotationY();
/**
 *    节点相关函数
 *    addChild , removeChild , setParent , removeFromParent ,
 *    reorderChild , sortAllChildren , setTag , 
 *    getCamera , isRunning , cleanup , 
 *    draw , visit , boundingBox ,
 *    onEnter , onEnterTransitionDidFinish , onExit
 */
//添加子节点.zOrder默认为0.
//tag为节点编号,可以通过tag获取子节点.
virtual void addChild(CCNode * child);
virtual void addChild(CCNode * child, int zOrder);
virtual void addChild(CCNode* child, int zOrder, int tag);
virtual CCNode * getChildByTag(int tag);
virtual CCArray* getChildren();                    //获得所有子节点,并以CCArray数组返回
virtual unsigned int getChildrenCount(void) const; //子节点个数
//删除子节点.
virtual void removeChild(CCNode* child);
virtual void removeChild(CCNode* child, bool cleanup);
virtual void removeChildByTag(int tag);
virtual void removeChildByTag(int tag, bool cleanup);
virtual void removeAllChildren();                        //删除所有节点
virtual void removeAllChildrenWithCleanup(bool cleanup); //cleanup为true则删除子节点的所有动作
//设置父节点.
virtual void setParent(CCNode* parent);
virtual CCNode* getParent();
//从父节点中移除该节点.
//Cleanup为true则删除当前节点的所有动作及回调函数.
virtual void removeFromParent();
virtual void removeFromParentAndCleanup(bool cleanup);
//重新设定节点的zOrder
virtual void reorderChild(CCNode * child, int zOrder);
//重新排序所有子节点
virtual void sortAllChildren();
//设置节点的tag编号
virtual void setTag(int nTag);
virtual int getTag() const;
//获取节点的CCCamera摄像机
virtual CCCamera* getCamera();
//判断节点是否在运行
virtual bool isRunning();
//停止所有运行的动作和回调函数
virtual void cleanup(void);
//绘制节点.
//draw里有好多绘制方法.如直线,曲线,矩形,圆等
virtual void draw(void);
//递归访问所有子节点,并重新绘制
virtual void visit(void);
//返回节点的矩形边界框
CCRect boundingBox(void);
//节点开始进入舞台时调用.即创建时调用.
virtual void onEnter();
//节点进入舞台后调用.即创建完后调用.
virtual void onEnterTransitionDidFinish();
//节点离开舞台时调用.即移除时调用
virtual void onExit();
/**
 *    Action动作相关
 *    runAction , stopAction , getActionByTag , numberOfRunningActions
 */
//执行动作
CCAction* runAction(CCAction* action);
//暂停动作
void stopAllActions(void);
void stopAction(CCAction* action);
void stopActionByTag(int tag);
CCAction* getActionByTag(int tag);         //根据tag标记获取动作
unsigned int numberOfRunningActions(void); //获取正在运行的动作数量
/**
 *    定时器相关函数
 *    scheduleUpdate , schedule , update
 */
//开启默认定时器.刷新次数为60次/秒.即每秒60帧.
//与update(float delta)回调函数相对应.
//给予定时器优先级priority.其中priority越小,优先级越高
void scheduleUpdate(void);
void scheduleUpdateWithPriority(int priority);
void unscheduleUpdate(void);      //取消默认定时器
virtual void update(float delta); //update为scheduleUpdate定时器的回调函数.
//设置自定义定时器.默认为每秒60帧.
//interval	:	每隔interval秒,执行一次.
//repeat	:	重复次数.
//delay		:	延迟时间,即创建定时器delay后开始执行.
void schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay);
void schedule(SEL_SCHEDULE selector, float interval);
void scheduleOnce(SEL_SCHEDULE selector, float delay); //只执行一次,delay秒后执行
void schedule(SEL_SCHEDULE selector);                  //默认为每秒60帧
void unschedule(SEL_SCHEDULE selector);                //取消定时器
void unscheduleAllSelectors(void);                     //取消所有定时器
void pauseSchedulerAndActions(void);                   //暂停所有定时器和动作
void resumeSchedulerAndActions(void);                  //恢复所有定时器和动作
//

    各个函数的作用,请自己摸索。

    导演CCDirector、场景CCScene、图层CCLayer、精灵CCSprite的概念请移步: cocos2dx基础篇(3)——第一个程序HelloWorld

    导演控制场景,场景控制图层,图层控制精灵,精灵控制动作。

    相互之间的关系框架如下图所示:

wKiom1PsQongTNMfAACrUrcHMUQ950.jpg

    由此看出:

        (1)整个游戏一般只有一个导演。

        (2)一个游戏可以由多个场景组成(菜单界面、游戏界面、游戏结束界面等),但是每次导演只能指导一个场景的运作。

        (3)一个场景可以由多个图层组成(背景层、道具层、英雄层、怪物层等,每个图层都可以由多个精灵元素组成(标签、按钮、菜单等)。

        (4)对于图层上的每个精灵元素,一般都附带相应的动作,可以带多个动作。如挥刀、使用魔法、跑、跳,以及放大、缩小、旋转等动作。

  • 导演类CCDirector

    参考博客:http://renpeng301.iteye.com/blog/1817548

http://blog.csdn.net/qiurisuixiang/article/details/8761191

    就和现实中的导演一样,这里的导演也是起到指导的作用的。导演在这里负责的就是让不同的场景切换,控制整个游戏的流程,包括开始,继续,暂停等。以及设置、获取系统信息,比如调整OpenGL相关的设置,获取屏幕的大小等。

    和CCScene、CCLayer、CCSprite等不同的是,导演类CCDirector是直接继承CCObject类的,而不是CCNode类。

    继承关系如下:

wKioL1PssoqB1MSnAABe5bnwaNI984.jpg

    主要函数如下:

class CC_DLL CCDirector : public CCObject, public TypeInfo
{
//获取全局唯一的CCDirector实例
//使用方法:CCDirector::sharedDirector()->replaceScene(scene);
static CCDirector* sharedDirector(void);
/**
 *	场景管理相关
 *	runWithScene , pushScene , popScene , popToRootScene , replaceScene ,
 *	pause , resume , end , 
 */
//指定进入Director的主循环运行的场景.
//ps:仅在运行第一个场景时调用,如果已经存在运行中的场景,不能调用本方法.
//本方法调用后将调用pushScene方法,然后调用startAnimation.
void runWithScene(CCScene *pScene);
//将运行中的场景暂停,并push到场景堆栈中,运行新的场景.
void pushScene(CCScene *pScene);
//从场景堆栈中pop出一个场景,替换现在正运行的场景,而运行中的场景将被删除.
void popScene(void);
//从场景堆栈中pop出所有场景,最后一个栈底的场景将替换现在正运行的场景,而运行中的场景将被删除.
void popToRootScene(void);
//使用新场景替换当前场景,而运行中的场景将被删除.
//PS:旧场景不压入堆栈,而是直接删除.
void replaceScene(CCScene *pScene);
void pause(void);  //暂停场景
void resume(void); //恢复被暂停的场景
void end(void);    //终止执行,释放运行中的场景. 而OpenGL view需要手动移除.
//获取当前运行的场景. 导演在某一时刻只能运行一个场景
inline CCScene* getRunningScene(void) { return m_pRunningScene; }
//是否暂停
inline bool isPaused(void) { return m_bPaused; }
//场景替换时是否接收到Cleanup事件.即是否清除场景.
//若新场景是push进来的,旧场景不会接收到Cleanup事件  
//若新场景是replace进来的,旧场景会接收到Cleanup事件
inline bool isSendCleanupToScene(void) { return m_bSendCleanupToScene; }
/**
 *	刷新帧数FPS相关
 *	setAnimationInterval , setDisplayStats
 */
//设置程序的FPS值. 即刷新频率,相连两帧的时间间隔.
//如dValue = 1.0/60.0 表示每秒60帧.
virtual void setAnimationInterval(double dValue) = 0;
inline double getAnimationInterval(void) { return m_dAnimationInterval; }
//是否在程序屏幕的左下角显示FPS值
inline void setDisplayStats(bool bDisplayStats) { m_bDisplayStats = bDisplayStats; }
//判断是否有显示FPS值
inline bool isDisplayStats(void) { return m_bDisplayStats; }
//获取每秒帧数
inline float getSecondsPerFrame() { return m_fSecondsPerFrame; }
//从CCDirector开机后,总共已经渲染了多少帧
inline unsigned int getTotalFrames(void) { return m_uTotalFrames; }
/**
 *	OpenGL图形渲染相关
 */
//设置CCEGLView.即OpenGL图形渲染
inline CCEGLView* getOpenGLView(void) { return m_pobOpenGLView; }
void setOpenGLView(CCEGLView *pobOpenGLView);
//设置OpenGL的Projection
void setProjection(ccDirectorProjection kProjection);
inline ccDirectorProjection getProjection(void) { return m_eProjection; }
//设置OpenGL的glViewport
void setViewport();
/**
 *	OpenGL View视图相关
 */
//获取OpenGL view的大小,单位为点.
//类似手机屏幕的大小.参照"主要控制类AppDelegate.cpp"中的图片.
CCSize getWinSize(void);
//获取OpenGL view的大小,单位为像素.
CCSize getWinSizeInPixels(void);
//获取OpenGL View可视区域大小,单位为点.
//类似程序的游戏区域.参照"主要控制类AppDelegate.cpp"中的图片.
CCSize getVisibleSize();
//获取可视区域的原点坐标.一般为程序游戏区域的左下角坐标.
CCPoint getVisibleOrigin();
//将UIKit坐标与OpenGL坐标的相互转换
//UIKit坐标:原点在屏幕的左上角. 从左到右,从上到下.
//OpenGL坐标:原点在屏幕的左下角.从左到右,从下到上.
CCPoint convertToGL(const CCPoint& obPoint); //转为GL坐标
CCPoint convertToUI(const CCPoint& obPoint); //转为UI坐标
/**
 *	其他
 */
//开始动画
virtual void startAnimation(void) = 0; 
//停止动画
virtual void stopAnimation(void) = 0; 
//绘制场景,每帧都会自动调用,无需手动.
void drawScene(void); 
//删除缓存数据。包括CCTextureCache、CCSpriteFrameCache、CCLabelBMFont缓存数据
void purgeCachedData(void);
}
//

    各个函数的作用,请自己摸索。

  • 场景类CCScene

    CCScene是继承与CCNode类的。作为场景类,它却只有两个函数init和create。因为场景就像是一个容器,将不同的图层(CCLayer)组合在一起,方便管理。

    一个游戏会有很多的场景,比如,主界面,游戏界面,载入界面等等都是一个场景。而每一个场景都是由多个图层组合在一起,形成一个完整的游戏画面。

    其实在 cocos2dx基础篇(3)——第一个程序HelloWorld 中就出现了CCScene的创建,以及将HelloWorld图层放入该CCScene中。

    继承关系如下:

wKioL1Pss2-QavZ1AABdGtAiOVY460.jpg

    以下为CCScene的源码:

class CC_DLL CCScene : public CCNode
{
public:
    CCScene();
    virtual ~CCScene();
    bool init();
    static CCScene *create(void);
};
bool CCScene::init()
{
    bool bRet = false;
     do {
         CCDirector * pDirector;
         CC_BREAK_IF( ! (pDirector = CCDirector::sharedDirector()) );
         this->setContentSize(pDirector->getWinSize());
         // success
         bRet = true;
     } while (0);
     return bRet;
}
CCScene *CCScene::create()
{
    CCScene *pRet = new CCScene();
    if (pRet && pRet->init()) {
        pRet->autorelease();
        return pRet;
    }
    else {
        CC_SAFE_DELETE(pRet);
        return NULL;
    }
}
//
  • 图层类CCLayer

    CCLayer继承于四个父类: CCNode, CCTouchDelegate, CCAccelerometerDelegate, CCKeypadDelegate。

    CCLayer不仅继承了CCNode的所有操作,还附加触屏、重力加速度计、支持输入功能。

    一个图层(CCLayer)可以包含多个元素,如标签(CCLabel)、菜单(CCMenu)、精灵(CCSprite)等等。

    注意:CCLayer的锚点默认为(0,0),即左下角。并且忽略锚点的设置,即使你setAnchorPoint了锚点,CCLayer的锚点也不会改变,依然是(0,0)。

    继承关系如下:

wKioL1Pss8TiI7ltAACvAcS0bKg560.jpg

    主要函数如下:

class CC_DLL CCLayer : public CCNode, public CCTouchDelegate, public CCAccelerometerDelegate, public CCKeypadDelegate
{
//创建一个静态图层对象
static CCLayer *create(void);
virtual void onEnter();                    //进入图层回调函数
virtual void onExit();                     //退出图层回调函数
virtual void onEnterTransitionDidFinish(); //场景转换后的回调函数
/**
 *	触屏事件相关
 *	分为单点触屏、多点触屏
 *	ccTouchBegan , ccTouchMoved , ccTouchEnded , ccTouchCancelled ,
 *	registerWithTouchDispatcher , TouchEnabled , TouchMode , TouchPriority
 */
//单点触屏接口的回调函数
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);
//注册触屏侦听事件
//默认是:CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(this,0);
//例如:
//	void CCLayer::registerWithTouchDispatcher() {
//		CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,INT_MIN+1,true); }
virtual void registerWithTouchDispatcher(void); 
//注册脚本触屏事件
virtual void registerScriptTouchHandler(int nHandler, bool bIsMultiTouches = false, int nPriority = INT_MIN, bool bSwallowsTouches = false); 
//注销脚本触屏事件
virtual void unregisterScriptTouchHandler(void); 
//设置是否接受触屏
virtual void setTouchEnabled(bool value); 
virtual bool isTouchEnabled();
//设置触屏模式. 同时响应,还是逐个响应
virtual void setTouchMode(ccTouchesMode mode);
virtual int getTouchMode();
//设置触屏的优先级. 默认为0,且priority越小优先级越高.
virtual void setTouchPriority(int priority);
virtual int getTouchPriority();
/**
 *	键盘输入相关
 */
//设置是否接受键盘输入
virtual bool isKeypadEnabled();
virtual void setKeypadEnabled(bool value);
//注册,注销 脚本键盘输入
void registerScriptKeypadHandler(int nHandler); 
void unregisterScriptKeypadHandler(void);
//返回键和菜单键的回调函数,需要设置接收键盘事件
virtual void keyBackClicked(void);
virtual void keyMenuClicked(void);
/**
 *	加速度计相关. 即重力感应.
 *	类似重力加速,不同的是加速度计分别在X轴,Y轴,Z轴都有一个相应的加速度.
 *	didAccelerate , registerScriptAccelerateHandler ,
 *	AccelerometerEnabled , AccelerometerInterval
 */
//加速度计信息
virtual void didAccelerate(CCAcceleration* pAccelerationValue); //加速度计信息
void registerScriptAccelerateHandler(int nHandler);             //注册加速度计
void unregisterScriptAccelerateHandler(void);                   //注销加速度计
//设置是否接受加速度计的信息
virtual bool isAccelerometerEnabled();
virtual void setAccelerometerEnabled(bool value);
virtual void setAccelerometerInterval(double interval);         //设置加速度计的时间间隔
}
//
  • 精灵类CCSprite

    参考博客:http://blog.csdn.net/jackystudio/article/details/12747385

    精灵说简单一点,其实就是一个2D的图片。并赋予图片各种属性以及特性。如大小、颜色、放缩、旋转、动作等。精灵一般都是放在图层(CCLayer)上面的,即一个图层(CCLayer)应当有许多的精灵存在。精灵可以用来当做背景、人物、鸟、白云等内容。

    CCSprite不仅继承了CCNode,还继承两个协议类:CCNodeRGBAProtocol和 CCTextureProtocol。

    其中CCNodeRGBAProtocol协议类主要负责颜色的管理;而CCTextureProtocol协议类主要负责纹理图片的管理。

    注意:精灵的锚点默认为(0.5,0.5),即中心点。

    继承关系如下:

wKiom1Pss2nyMaS9AACDXa-r1wM481.jpg

    主要函数如下:

class CC_DLL CCSprite : public CCNodeRGBA, public CCTextureProtocol
{
/**
 *	创建精灵相关create
 *	create , createWithTexture , 
 *	createWithSpriteFrame , createWithSpriteFrameName
 */
//注意事项:
//从大图中截取某一区域的图片的CCRect rect的构造应该是这样的:
//		CCRect("小图左上角坐标x", "小图左上角坐标y", 小图宽, 小图高)
//这与cocos2dx的坐标系是不一样的
static CCSprite* create();                                                     //默认创建空精灵对象
static CCSprite* create(const char *pszFileName);                              //图片文件
static CCSprite* create(const char *pszFileName, const CCRect& rect);          //截取图片文件中某一区域图片
static CCSprite* createWithTexture(CCTexture2D *pTexture);                     //纹理图片
static CCSprite* createWithTexture(CCTexture2D *pTexture, const CCRect& rect); //截取纹理图片中某一区域图片
static CCSprite* createWithSpriteFrame(CCSpriteFrame *pSpriteFrame);           //精灵帧. 精灵帧一般是从plist中读取的
static CCSprite* createWithSpriteFrameName(const char *pszSpriteFrameName);    //精灵帧的名字
/**
 *	初始化精灵相关init
 *	一般在精灵create的时候,就会调用相对应的init函数. 
 *	init , initWithTexture , 
 *	initWithSpriteFrame , initWithSpriteFrameName , 
 *	initWithFile
 */
virtual bool init(void);                                                               //默认初始化
virtual bool initWithTexture(CCTexture2D *pTexture);                                   //纹理图片
virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect);               //截取纹理图片中某一区域图片
virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect, bool rotated); //截取纹理图片中某一区域图片,是否旋转
virtual bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame);                         //精灵帧. 精灵帧一般是从plist中读取的
virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName);                  //精灵帧的名字
virtual bool initWithFile(const char *pszFilename);                                    //图片文件
virtual bool initWithFile(const char *pszFilename, const CCRect& rect);                //截取图片文件中某一区域图片
/**
 *	继承于节点类CCNode的函数
 *	Scale , Position , Rotation , Skew , VertexZ
 *	addChild , removeChild , reorderChild , sortAllChildren , 
 *	AnchorPoint , Visible , draw
 */
virtual void setScale(float fScale);
virtual void setScaleX(float fScaleX);
virtual void setScaleY(float fScaleY);
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 setVertexZ(float fVertexZ);
virtual void addChild(CCNode *pChild);
virtual void addChild(CCNode *pChild, int zOrder);
virtual void addChild(CCNode *pChild, int zOrder, int tag);
virtual void removeChild(CCNode* pChild, bool bCleanup);
virtual void removeAllChildrenWithCleanup(bool bCleanup);
virtual void reorderChild(CCNode *pChild, int zOrder);
virtual void sortAllChildren();
virtual void setAnchorPoint(const CCPoint& anchor);
virtual void ignoreAnchorPointForPosition(bool value);
virtual void setVisible(bool bVisible);
virtual void draw(void);
/**
 *	继承于颜色协议类CCNodeRGBA的函数
 *	Color , Opacity
 */
//RGB颜色
virtual void setColor(const ccColor3B& color3);                  //设置颜色
virtual void updateDisplayedColor(const ccColor3B& parentColor); //传递颜色
//透明度
virtual void setOpacity(GLubyte opacity);                   //设置透明度
virtual void setOpacityModifyRGB(bool modify);              //设置透明度是否随RGB颜色的变化而变化
virtual bool isOpacityModifyRGB(void);                      //判断透明度是否随RGB颜色的变化而变化
virtual void updateDisplayedOpacity(GLubyte parentOpacity); //传递透明度
/**
 *	继承于纹理协议类CCTextureProtocol的函数
 *	Texture , BlendFunc
 */
//设置精灵的纹理图片
virtual void setTexture(CCTexture2D *texture);
virtual CCTexture2D* getTexture(void);
//设置颜色混合方式
inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = blendFunc; }
inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; }
/**
 *	批节点CCSpriteBatchNode相关的函数
 *	CCSpriteBatchNode是精灵集合类,都使用同一张纹理图片.
 *	故将这些精灵成批进行渲染,以提高渲染速度.
 */
virtual void updateTransform(void);                               //更新四个值:position(x,y), rotation, scale
virtual CCSpriteBatchNode* getBatchNode(void);                    //如果精灵是由批节点渲染的,则返回批节点
virtual void setBatchNode(CCSpriteBatchNode *pobSpriteBatchNode); //设置批节点,不推荐使用
/**
 *	纹理Texture相关的函数
 */
//设置纹理区域
virtual void setTextureRect(const CCRect& rect);
virtual void setTextureRect(const CCRect& rect, bool rotated, const CCSize& untrimmedSize);
virtual void setVertexRect(const CCRect& rect);
/**
 *	精灵帧SpriteFrames & 动画Animation相关的函数
 *	
 */
virtual void setDisplayFrame(CCSpriteFrame *pNewFrame);  //设置新的显示精灵帧
virtual bool isFrameDisplayed(CCSpriteFrame *pFrame);    //返回精灵帧是否正在显示
virtual CCSpriteFrame* displayFrame(void);               //返回当前显示的精灵帧
//通过动画帧的第frameIndex那一帧来设置显示精灵帧
//动画帧是从CCAnimationCache中读取的
virtual void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex);
/**
 * 	属性相关的函数
 */
//设置精灵是否需要更新
inline virtual void setDirty(bool bDirty) { m_bDirty = bDirty; }
inline virtual bool isDirty(void) { return m_bDirty; }
//返回四个值的信息:坐标(x,y),顶点,颜色
inline ccV3F_C4B_T2F_Quad getQuad(void) { return m_sQuad; }
//判断纹理是否被旋转
inline bool isTextureRectRotated(void) { return m_bRectRotated; }
//设置精灵在地图集TextureAtlas中的索引
inline void setAtlasIndex(unsigned int uAtlasIndex) { m_uAtlasIndex = uAtlasIndex; }
inline unsigned int getAtlasIndex(void) { return m_uAtlasIndex; }
//返回精灵区域,单位为点
inline const CCRect& getTextureRect(void) { return m_obRect; }
//如果采用批渲染,设置纹理地图集
inline void setTextureAtlas(CCTextureAtlas *pobTextureAtlas) { m_pobTextureAtlas = pobTextureAtlas; }
inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas; }
//获取偏移值
inline const CCPoint& getOffsetPosition(void) { return m_obOffsetPosition; }
//设置是否翻转
void setFlipX(bool bFlipX);
void setFlipY(bool bFlipY);
bool isFlipX(void);
bool isFlipY(void);
};
//

    精灵在整个游戏中的使用应该是最频繁的,它的功能也是最丰富的,所以需要花大把时间来摸索。

  • 坐标类CCPoint

    CCPoint既可以表示坐标点,又可以表示一个坐标向量。

    同时CCPoint对运算符进行的重载,可以很方便的完成CCPoint的赋值、加减乘除等操作。另外还有与坐标向量相关的:距离、角度、点积、叉积、投影、标准化等操作。

    当然cocos2dx也提供了许多有关CCPoint运算的宏定义与常量,如CCPointZero,CCPointMake,ccp,ccpAdd,ccpSub等。

    CCPoint可以使一个坐标点,也可以是一个坐标向量。

wKioL1Ps8TCROQmnAAAu3KSrIzs480.jpg

    主要函数如下:

class CC_DLL CCPoint
{
public:
    float x; //X坐标
    float y; //Y坐标
/**
 *	构造函数
 */
CCPoint();
CCPoint(float x, float y);
CCPoint(const CCPoint& other);
CCPoint(const CCSize& size);
/**
 *	运算符重载
 *	直接像int型一样相加减.如 p3 = p1 + p2
 */
CCPoint& operator= (const CCPoint& other);     //(other.x , other.y)
CCPoint& operator= (const CCSize& size);       //(size.width , size.height)
CCPoint operator+(const CCPoint& right) const; //(x1+x2 , y1+y2)
CCPoint operator-(const CCPoint& right) const; //(x1-x2 , y1-y2)
CCPoint operator-() const;                     //(-x , -y)
CCPoint operator*(float a) const;              //(x*a , y*a)
CCPoint operator/(float a) const;              //(x/a , y/a)
/**
 *	CCPoint的相关函数
 *	setPoint , forAngle , equals , fuzzyEquals ,
 *	getLength , getDistance , getAngle , getPerp , rotateByAngle , 
 *	dot , cross , project , normalize ,
 *	rotate , unrotate , lerp
 */
//设置坐标
void setPoint(float x, float y);
//根据角度,计算向量坐标x=cos(a) , y=sin(a)
//这是一个static静态函数
static inline CCPoint forAngle(const float a) { return CCPoint(cosf(a), sinf(a)); }
//判断是否与target相等
bool equals(const CCPoint& target) const;
//判断target是否在坐标点模糊偏差为var的范围内.
//if( (x - var <= target.x && target.x <= x + var) && 
//	  (y - var <= target.y && target.y <= y + var) ) 
//		return true;
bool fuzzyEquals(const CCPoint& target, float variance) const;
//与原点的距离
//与原点的距离平方,即x*x + y*y.
//与other的距离
//与other的距离平方
inline float getLength() const { return sqrtf(x*x + y*y); };
inline float getLengthSq() const { return dot(*this); };
inline float getDistance(const CCPoint& other) const { return (*this - other).getLength(); };
inline float getDistanceSq(const CCPoint& other) const { return (*this - other).getLengthSq(); };
//与X轴的夹角; 与other向量的夹角. 单位为:弧度
inline float getAngle() const { return atan2f(y, x); };
float getAngle(const CCPoint& other) const;
//Perp逆时针旋转90度; RPerp顺时针旋转90度
inline CCPoint getPerp() const { return CCPoint(-y, x); };
inline CCPoint getRPerp() const { return CCPoint(y, -x); };
//以pivot为圆心,将坐标逆时针旋转angle度
CCPoint rotateByAngle(const CCPoint& pivot, float angle) const;
//计算两点的 "点积dot" 和 "叉积cross"
inline float dot(const CCPoint& other) const { return x*other.x + y*other.y; };
inline float cross(const CCPoint& other) const { return x*other.y - y*other.x; };
//向量在other上的投影向量
//公式参考: http://www.cnblogs.com/graphics/archive/2010/08/03/1791626.html
inline CCPoint project(const CCPoint& other) const { return other * (dot(other)/other.dot(other)); };
//向量标准化,即长度为1. PS: 如果是零向量,返回(1,0);
inline CCPoint normalize() const {
	float length = getLength();
	if(length == 0.0) return CCPoint(1.0f, 0);
	return *this / getLength();
};
/**
 *	未知函数
 */
//复合乘法???
//angle = this.getAngle() + other.getAngle()
//length = this.getLength() * other.getLength()
inline CCPoint rotate(const CCPoint& other) const { 
	return CCPoint(x*other.x - y*other.y, x*other.y + y*other.x); 
};
//反复合乘法???
//angle = this.getAngle() - other.getAngle()
//length = this.getLength() * other.getLength()
inline CCPoint unrotate(const CCPoint& other) const { 
	return CCPoint(x*other.x + y*other.y, y*other.x - x*other.y); 
};
//线性内插法???
inline CCPoint lerp(const CCPoint& other, float alpha) const {
	return *this * (1.f - alpha) + other * alpha;
};
};
//
  • 尺寸大小类CCSize

    CCSize比较简单,只是一个用来表示尺寸大小的类。宽为width,高为height。

    和CCPoint一样,也对运算符进行了重载。

    目前好像就找到两个宏定义与常量:CCSizeMake 和 CCSizeZero。

    主要函数如下:

class CC_DLL CCSize
{
public:
    float width;  //宽度
    float height; //高度
/**
 *	构造函数
 */
CCSize();                          //(0 , 0)
CCSize(float width, float height); //(width , height)
CCSize(const CCSize& other);       //(other.width , other.height)
CCSize(const CCPoint& point);      //(point.x , point.y)
/**
 *	运算符重载
 *	直接像int型一样相加减.如 p3 = p1 + p2
 */
CCSize& operator= (const CCSize& other);     //this = other
CCSize& operator= (const CCPoint& point);    //width=point.x , height=point.y
CCSize operator+(const CCSize& right) const; //width+right.width , height+right.height
CCSize operator-(const CCSize& right) const; //width-right.width , height-right.height
CCSize operator*(float a) const;             //width*a , height*a
CCSize operator/(float a) const;             //width/a , height/a
/**
 *	CCSize的相关函数
 *	setSize , equals
 */
//设置尺寸大小
void setSize(float width, float height);
//判断两尺寸是否相等
bool equals(const CCSize& target) const;
};
//
  • 矩形类CCRect

    CCRect是一个矩形类。包含:起始坐标(左下角坐标)CCPoint、矩阵的尺寸大小CCSize两个属性。

    CCRect只对“=”运算符进行了重载。目前好像就找到两个宏定义与常量:CCRectMake,CCRectZero。

    值得注意的是CCRect类中:

        intersectsRect函数,可以用作两个CCRect矩形是否相交,即碰撞检测。

containsPoint 函数,可以用作判断点CCPoint是否在CCRect矩形中。

wKiom1Ps83TytTN3AABEUdrO2HE928.jpg

    若用CCRect来作为创建CCSprite精灵的参数,需要注意,从大图中截取某一区域的图片的CCRect rect的构造应该是这样的:

    CCRect("小图左上角坐标x", "小图左上角坐标y", 小图宽, 小图高);

    这与cocos2dx的坐标系是不一样的。

    如下图所示:

wKioL1P1nT-juGOSAADARBo6V0E608.jpg

    主要函数如下:

class CC_DLL CCRect
{
public:
    CCPoint origin; //起始坐标: 左下角坐标
    CCSize  size;   //尺寸大小
/**
 *	构造函数
 */
CCRect();
CCRect(float x, float y, float width, float height);
CCRect(const CCRect& other);
/**
 *	运算符重载
 *	只重载了 “=” 运算符
 */
CCRect& operator= (const CCRect& other);
/**
 *	CCRect的相关函数
 *	setRect , getMinX , getMidX , getMaxX
 *	equals , containsPoint , intersectsRect
 */
//设置矩形
void setRect(float x, float y, float width, float height);
//
float getMinX() const; //origin.x
float getMidX() const; //origin.x + size.width/2
float getMaxX() const; //origin.x + size.width
float getMinY() const; //origin.y
float getMidY() const; //origin.y + size.height/2
float getMaxY() const; //origin.y + size.height
//判断是否与rect相同. 原点相同,尺寸相同.
bool equals(const CCRect& rect) const;
//判断point是否包含在矩形内或四条边上
bool containsPoint(const CCPoint& point) const;
//判断矩形是否相交. 常常用作碰撞检测.
bool intersectsRect(const CCRect& rect) const;
};
//
  • 数组类CCArray

    继承于CCObject类,本质是将ccArray相关的函数操作进行了封装处理。对于ccArray有兴趣的自己了解一下。

    宏定义:

        CCARRAY_FOREACH(CCArray* arr, CCObject* obj);         //遍历CCArrray数组
        CCARRAY_FOREACH_REVERSE(CCArray* arr, CCObject* obj); //逆序遍历

    CCArray类终点数据类型为ccArray:

typedef struct _ccArray {
	unsigned int num; //元素个数
	unsigned int max; //数组容量. 和num不一样,一般max>=num.
	//二重指针,相当于是指向 CCobject*数组 的指针.
	//每个元素用arr[i]来读取,这是一个指向第i个索引的CCObject*
	CCObject** arr; 
} ccArray;
//

    当然在我们添加元素的时候,不一定非是CCObject类型不可,可以是其他类型,如CCNode。

    CCArray类的主要函数如下:

class CC_DLL CCArray : public CCObject
{
public:
	ccArray* data; //元素是一个ccArray类型
public:
/**
 *		构造、创建、初始化函数
 *		CCArray , create , init
 */
//构造函数
CCArray();
CCArray(unsigned int capacity);
//创建函数
static CCArray* create();
static CCArray* create(CCObject* pObject, ...);
static CCArray* createWithObject(CCObject* pObject);
static CCArray* createWithCapacity(unsigned int capacity);
static CCArray* createWithArray(CCArray* otherArray);
//通过plist文件导入数组
static CCArray* createWithContentsOfFile(const char* pFileName);
//同上. 但不设置autorelease自动释放内存,需要手动调用release()释放
static CCArray* createWithContentsOfFileThreadSafe(const char* pFileName);
//初始化函数
bool init();
bool initWithObject(CCObject* pObject);
bool initWithObjects(CCObject* pObject, ...);
bool initWithCapacity(unsigned int capacity);
bool initWithArray(CCArray* otherArray);
/**
 *		查询
 *		count , capacity ,
 *		indexOfObject , objectAtIndex , lastObject , randomObject , 
 *		containsObject , isEqualToArray
 */
unsigned int count() const;    //元素个数
unsigned int capacity() const; //数组容量
//用元素查找的索引(下标从0开始). 
//若不存在,返回无符号整形最大值UINT_MAX=0xFFFFFFFF
unsigned int indexOfObject(CCObject* object) const;
//用索引查找元素
CCObject* objectAtIndex(unsigned int index); 
CCObject* lastObject();                      //返回最后一个元素
CCObject* randomObject();                    //返回随机一个元素
bool containsObject(CCObject* object) const; //判断object是否存在于CCArray中
bool isEqualToArray(CCArray* pOtherArray);   //两数组每个索引位置上的元素是否全部相同
/**
 *		添加删除元素
 *		addObject , insertObject
 *		removeObject , fastRemoveObject , removeAllObjects
 */
//添加元素
void addObject(CCObject* object);
void addObjectsFromArray(CCArray* otherArray);
void insertObject(CCObject* object, unsigned int index);
//删除元素. bReleaseObj表示是否释放资源
//被删除的元素后面的元素都往前挪动一个位置
void removeLastObject(bool bReleaseObj = true);                        //删除最后一个元素
void removeObject(CCObject* object, bool bReleaseObj = true);          //删除object元素
void removeObjectAtIndex(unsigned int index, bool bReleaseObj = true); //删除索引为index的元素
void removeObjectsInArray(CCArray* otherArray);                        //删除与otherArray数组中相同的所有元素
//快速删除元素.
//和普通删除不同的是: 只将最后一个元素覆盖被删除的元素,不进行元素挪动
void fastRemoveObject(CCObject* object);          //快速删除object元素
void fastRemoveObjectAtIndex(unsigned int index); //快速删除索引为index的元素
//删除所有元素
void removeAllObjects(); 
/**
 *		重排数组
 *		exchangeObject , replaceObjectAtIndex
 *		reverseObjects , reduceMemoryFootprint
 */
//交换两个元素的位置
void exchangeObject(CCObject* object1, CCObject* object2);
void exchangeObjectAtIndex(unsigned int index1, unsigned int index2);
//用pObject替换索引为index的元素
void replaceObjectAtIndex(unsigned int uIndex, CCObject* pObject, bool bReleaseObject = true);
//将数组元素反序, a b c d --> d c b a.
void reverseObjects();
//缩小内存,将内存缩小为 max = num
void reduceMemoryFootprint();
};
//
你可能感兴趣的内容
MySQL 基础面试题 收藏,3603 浏览
Git简单入门教程 收藏,4449 浏览
0条评论

dexcoder

这家伙太懒了 <( ̄ ﹌  ̄)>
Owner