Cocos2d 基础知识

本文介绍了Cocos2d的基础知识,包括Director类、Scene、Layer、Sprite的使用,详细讲解了Menu和MenuItem、Label、ProgressTimer、动作(Action)的各类操作,如旋转、移动、缩放、进度条等,并提到了场景跳转的动画效果和音乐播放控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)Director类(导演类):  

(2)Scene类(场景类):

(3)Layer类(图层类):

(4)Sprite类(精灵类):

//创造精灵

auto sp=Sprite::create("circle.png");

  this->setTexture(str);//换图片


1、Menu和MenultemMenu:菜单它是Menultem的容器

Menultem:菜单项

MenultemToggle:可以容纳多个Menultem的子类,点击可以切换下一个显示的按钮。

MenultenImage:Menultem的子类,就是我们平时看到的图片按钮。

MenultemAtlasFont: 我们平时看到的汉字按钮

Menultem的子类有:MenultemLabel、MenultemAtlasFont、MenultemFont、MenultemSprite、Menultenlmage、MenultemToggle

menu->setPosition(Vec2::ZERO);


setCallback  回调函数,用于响应菜单



2、Label(字体):

a)使用系统字体创建auto label=Label::createwithSystemFont中泰教育“fonts/Marker Felt.ttf”30

b)使用BMF字体创建

auto bmfLabel=Label::createwithBMFont(“FontBMFont.fnt”,“植物大战僵尸B2”;

c)使用charmap创建

auto charmapLabel=Label::createwithCharMap(“FontALtas.png”,14,21,48);/ 第一个字符acall

charmapLabel->setPositionVec2240160));

charmapLabel->setString(“123456”);

this->addChildcharmaplLabe1;


3、ProgressTimer 进度条百分比  Percentage

a)圆周形进度条

auto progressCircle=ProgressTimer::create(Sprite::create(“circle.png”));

progressCircle->setPositionVec2240160));

this->addChildprogressCircle;

progressCircle->setPercentage60;//显示百分比

progressCircle->setType(ProgressTimer::Type::RADIAL);//进度条类型

//auto action_1=ProgressFromTo::create(3,0,100);//进度条动作 3秒从0-100

// progressCircle->runAction(action_1);


b)长方形进度条

auto progressLong =ProgressTimer::create(Sprite::create(“Long.png”));

progressLong->setPosition(Vec2(240,160));

progressLong ->setType(ProgressTimer::Type::BAR); //进度条类型

progressLong->setMidpoint(Vec2(0,0.5)); //进度条方向 从0开始

progressLong->setBarChangeRate(Vec2(1,0)); //进度 条 变化率  到(1,0)

progressLong->setPercentage(50);

this->addChild(progressLong);

// auto action_2=ProgressFromTo::create(3,0,100);

// progressLong->runAction(action_2);


LoadingBar进度条       百分比Percent

我们看到游戏的资源加载界面的进度显示就是通过这个控件完成的。

(人物血量)

auto loadingBar =LoadingBar::create("loadingbar.png");

 loadingBar->setPosition(Vec2(240,280));

        this->addChild(loadingBar,10);

        schedule([=](float dt) {

            static int time=1;

            if (time>=100)

            {

                unschedule("loadingbar");

            }

            time+=10;

            loadingBar->setPercent(time);//百分比


        },1,"loadingbar");




Schedule//时间调度器


开启一个时间调度器不断调用updateZT,间隔为0.5s,重复次数为10次,第一次执行会延迟5s 

schedule(CC_CALLBACK_1(Helloworld::updateZT,this),0.5,10,5,updateZT”);

 schedule([=](float dt) {

        static int time=1;

        if (time>=100)

        {

            

            unschedule("loadingbar");

            


           auto scene =My2::createScene();

           Director::getInstance()->pushScene(scene);//入栈

            SimpleAudioEngine::getInstance()->pauseBackgroundMusic();//暂停;

        

        }

        time+=10;

        loadingBar->setPercent(time);

    

    },1,"loadingbar");



Cocos2d-X的动作动作(Action):

    (1)动作是对Node以及其子类的操作实现实体,也就是说Node和其子类都可以“执行动作”。

    (2)动作具有传递性,当一个节点在做动作,那么它的子节点也会相应的做出该动作,这就是传递,更是符合正常思维。

auto sp=Sprite::create("ball1.jpg");

    sp->setPosition(Vec2(160, 240));

    this->addChild(sp,10);

    

    auto sp1=RotateBy::create(0.5, 0, 180);

    

    sp->runAction(sp1);


    1.1持续动作(ActionInterval):需要一定时间去执行的动作基本动作:

(1)MoveTo和MoveBy    //移动位置            移动方向

(2)RotateTo和RotateBy  //旋转角度到       //旋转角度

(3)ScaleTo和ScaleBy    //比例(放大/缩小) //比例(放大/缩小)

(4)JumpTo和JumpBy       跳跃

(5)Blink//Blinkauto      闪烁

(6)reverse   //相反

函数auto _moveBy=MoveBy::create(2,Vec2(100,0));

auto _moveByBack=_moveBy->reverse();

testsp->runAction(_moveByBack);

克隆动作

auto heroSprite = Sprite::create("herosprite.png");
auto enemySprite = Sprite::create("enemysprite.png");
// create an Action
auto moveBy = MoveBy::create(10, Vec2(400,100));

// run it on our hero
heroSprite->runAction(moveBy);

// run it on our enemy
enemySprite->runAction(moveBy->clone()); 

    

(7)BezierTo和BezierBy     //贝塞尔曲线

    样条曲线动作:

    (8)CardinalSplineTo和CardinalSplineBy    

    (8)CatmullRomTo和CatmullRomBy   

 缓冲动作类


(1)基本缓冲动作:Easeln、EaseOut、EaselnOut//EaseIn

第一个参数是我们的Action对象,第二个参数是速率参数

auto _moveBy=MoveBy::create(3,Vec2(200,0));

 auto _easeIn=EaseIn::create(_moveBy,0.1);

testsp->runAction(_easeIn);


(2)指数缓冲动作:

EaseExponentialln、EaseExponentialOut.EaseExponentiallnOutyan

下面分别是它们的速度曲线图


//EaseExponentialInauto _moveBy=MoveBy::create(3,Vec2(200,0));

  auto _easeExponentialIn =EaseExponentialIn::create(_moveBy);

testSp->runAction(_easeExponentialIn);

    

(3)赛因缓冲动作:EaseSineln、EaseSineOut、EaseSinelnOut

速度曲线图分别如下:

    C。

(4)跳跃缓冲动作:EaseBounceln、EaseBounceOut、EaseBouncelnOutraA


(5)弹性缓冲动作:EaseElasticIn、EaseElasticOut、EaseElasticlnOut

速度曲线如下:


 (6)回震缓冲动作:EaseBackIn、EaseBackOut、EaseBacklnOut

   

 组合动作类:


(1)动作延时:DelayTime让一个节点在一段时间内做一个空的动作,就是让其等待一段时间。

//DelayTime 动作延时

auto _delayTime=DelayTime::create(2);

testSp->runAction(_delayTime);


(2)序列动作:Squence将一个或多个动作组合起来,按照固定顺序执行。

    //序列动作类Sequenceauto _moveBy =MoveBy::create(2,Vec2(100,0));

    auto _scaleBy=ScaleBy::create(2,2);

auto _seqAction=Sequence::create(_moveBy,_scaleBy,NULL);

testSp->runAction(_seqAction);

    

(3)同步动作类:Spawn将一个或者多个动作组织起来,让节点同时运行这些动作。(注意如果这些动作如果有冲突就会产生不可预料的结果)


(4)重复动作类:Repeat和RepeatForver

Repeat让一个动作重复执行n次,RepeatForver让一个动作一直重复下去

//Repeat和RepeatForver

auto _scaleBy =ScaleBy::create(1,2);

auto _repeat=Repeat::create(_scaleBy,2);

//auto _action=Sequence::create(_scaleBy,_scaleBy->reverse(),NULL);

//auto _repeatForver=RepeatForever::create(_action);

testSp->runAction(_repeat);

    



(5)执行者改变动作:TargetedAction

//改变动作执行者TargetedActionauto 

targetSp=Sprite::create(“CloseNormal.png”);

targetSp->setPosition(Vec2(100,200));

this->addChild(targetSp);

auto _scaleBy=ScaleBy::create(2,2);

auto _targetAction=TargetedAction::create(targetSp,_scaleBy); 精灵   动作

testsp->runAction(_targetAction);


(6)进度条专属动作:ProgressTo和ProgressFromTo


//auto action_2=ProgressFromTo::create(3,0,100);

// auto action_2=ProgressTo::create(3,100);

progressTime_2->runAction(action_2);

    

1.2ActionIntant:


瞬时动作(执行瞬间完成,不需要时间)

(1)CallFunc

auto _callFunc=CallFunc::create([](){

    log(“This is a CallFunc!!!\r\n”);});

auto _rotateBy =RotateBy::create(2,360);

auto _seq=Sequence::create(_rotateBy,_callFunc,NULL);

testSp->runAction(_seq);

 (2)CallFuncN

auto _callFUncN=CallFuncN::create([](Ref* sender){

    Node*_sender=(Node*)sender;_sender->runAction(ScaleBy::create(2,2));

    });

    auto _rotateBy=RotateBy::create(2,360);auto _seq=Sequence::create(_rotateBy,_callFUncN,NULL);

    testSp->runAction(_seq);

    

1.3其他动作

(1)Speed//速率

auto _moveBy =MoveBy::create(2,Vec2(200,0));

auto _speed=Speed::create(_moveBy,2);

testSp->runAction(_speed);

(2)Follow//follow

auto follow=Follow::createtestSp;

folLow->setBoundarysettrue;用来开启或关闭追踪

this->runAction_follow;

auto _moveTo=MoveTo::create2Vec2400100));

    testsp->runAction_moveTo;

.1Sprite高级知识讲解


(1)纹理和纹理缓存(Texture2D和TextureCache)

可以看成贴图,最好别用,容易图片变形,推介用精灵帧

//TextureCache利用addImage来加载图片到缓存中并返回一个纹理TextureCache*_texTureCache=Director::getInstance()->getTextureCache();

Texture2D*_texTure=_texTureCache->addImage“fish_2.png”;

auto sp=Sprite::createwithTexture_texTure;

sp->setPositionVec2200200));

  this->addChildsp;

    



(2)精灵帧和精灵帧缓存(SpriteFrame和SpriteFrameCache)

//SpriteF rameCache单例通常用加载纹理集来实现动画的加载

auto _spriteFrameCache=SpriteFrameCache::getInstance();// 精灵帧缓存

_spriteFrameCache->addSpriteFrameswithFile“fishes.plist”“fishes.png”;

auto _spriteFrame=_spriteFrameCache->getSpriteF rameByName“fish_3.png”;

auto _sp=Sprite::createwithSpriteFrame_spriteFrame;

sp->setPositionVec2200200));

this->addChild_sp;

1.2创建桢动画

    (1)将多张散图合成一张纹理集

    (2)使用精灵帧缓存将大图中的小图读取到缓存中

    (3)将多张精灵帧创建为动画帧

    (4)将多张动画帧做成动画

    (5)将动画转成动作

    (6)让精灵执行这个动作

auto _spriteFrameCache=SpriteFrameCache::getInstance();//精灵帧缓存

     _spriteFrameCache->addSpriteFramesWithFile("fishes.plist", "fishes.png");

     Vector<AnimationFrame*>_animationFrameVector;//动画容器

     for (int i=1; i<=6; ++i)

     {

      string str=StringUtils::format("fish_%d.png",i);

     //找精灵帧

     auto _spriteFrame=_spriteFrameCache->getSpriteFrameByName(str);

     //精灵帧->动画帧

     auto aniFrame=AnimationFrame::create(_spriteFrame, 0.2,ValueMap());

     _animationFrameVector.pushBack(aniFrame);//把动画帧缓存动画容器

     }

     //动画容器中的动画帧->动画

     auto _animation=Animation::create(_animationFrameVector,1.0f,5);

     //动画->动作

     auto _animate=Animate::create(_animation);

跳转场景

压栈(push)与出栈(pop

    auto scene = MyScene:: createScene(); // 对将要进入场景的声明

    Director::getInstance()->pushScene(scene);

出栈就不需要指明类了,从哪里来到哪里去

Director::getInstance()->popScene();

注意:push pop 成对出现  使用进出栈,原场景会保留离开时的数据,会增大CPU的消耗

使用导演类来控制

auto scene = MyScene::creatScene();

Director::getInstance()->replaceScene(scene);

从场景MyScene到场景HelloWorld均是这样操作,主要是replaceScene()函数的使用

注意:区别于进出栈,不做数据的保留,跳转时原场景数据当即被释放

2.test中的效果总结

CCTransitionJumpZoom::transitionWithDuration(t, s);//跳跃式,本场景先会缩小,然后跳跃进来

CCTransitionFade::transitionWithDuration(t, s);//淡出淡入,原场景淡出,新场景淡入

CCTransitionFade::transitionWithDuration(t, s, ccWHITE);//如果上一个的函数,带3个参数,则第三个参数就是淡出淡入的颜色

CCTransitionFlipX::transitionWithDuration(t, s, kOrientationLeftOver);//x轴左翻

CCTransitionFlipX::transitionWithDuration(t, s, kOrientationRightOver);//x轴右翻

CCTransitionFlipY::transitionWithDuration(t, s, kOrientationUpOver);//y轴上翻

CCTransitionFlipY::transitionWithDuration(t, s, kOrientationDownOver);//y轴下翻

CCTransitionFlipAngular::transitionWithDuration(t, s, kOrientationLeftOver);//有角度转的左翻

CCTransitionFlipAngular::transitionWithDuration(t, s, kOrientationRightOver);//有角度转的右翻

CCTransitionZoomFlipX::transitionWithDuration(t, s, kOrientationLeftOver);//带缩放效果x轴左翻

CCTransitionZoomFlipX::transitionWithDuration(t, s, kOrientationRightOver);//带缩放效果x轴右翻

CCTransitionZoomFlipY::transitionWithDuration(t, s, kOrientationUpOver);//带缩放效果y轴上翻

CCTransitionZoomFlipY::transitionWithDuration(t, s, kOrientationDownOver);//带缩放效果y轴下翻

CCTransitionZoomFlipAngular::transitionWithDuration(t, s, kOrientationLeftOver);//带缩放效果/有角度转的左翻

CCTransitionZoomFlipAngular::transitionWithDuration(t, s, kOrientationRightOver);//带缩放效果有角度转的右翻

CCTransitionShrinkGrow::transitionWithDuration(t, s);//交错换

CCTransitionRotoZoom::transitionWithDuration(t, s);//转角换

CCTransitionMoveInL::transitionWithDuration(t, s);//新场景从左移入覆盖

CCTransitionMoveInR::transitionWithDuration(t, s);//新场景从右移入覆盖

CCTransitionMoveInT::transitionWithDuration(t, s);//新场景从上移入覆盖

CCTransitionMoveInB::transitionWithDuration(t, s);//新场景从下移入覆盖

CCTransitionSlideInL::transitionWithDuration(t, s);//场景从左移入推出原场景

CCTransitionSlideInR::transitionWithDuration(t, s);//场景从右移入推出原场景

CCTransitionSlideInT::transitionWithDuration(t, s);//场景从上移入推出原场景

CCTransitionSlideInB::transitionWithDuration(t, s);//场景从下移入推出原场景

以下三个需要检测opengl版本是否支持CCConfiguration::sharedConfiguration()->getGlesVersion() <= GLES_VER_1_0如果为真则为不支持

CCTransitionCrossFade::transitionWithDuration(t,s);//淡出淡入交叉,同时进行

CCTransitionRadialCCW::transitionWithDuration(t,s);//时针切入

CCTransitionRadialCW::transitionWithDuration(t,s);//时针切入

以下两个需要先设置摄像机,使用CCDirector::sharedDirector()->setDepthTest(true);

CCTransitionPageTurn::transitionWithDuration(t, s, false);//翻页,前翻

CCTransitionPageTurn::transitionWithDuration(t, s, true);//翻页,后翻

CCTransitionFadeTR::transitionWithDuration(t, s);//向右上波浪

CCTransitionFadeBL::transitionWithDuration(t, s);//向左下波浪

CCTransitionFadeUp::transitionWithDuration(t, s);//向上百叶窗

CCTransitionFadeDown::transitionWithDuration(t, s);//向下百叶窗

CCTransitionTurnOffTiles::transitionWithDuration(t, s);//随机小方块

CCTransitionSplitRows::transitionWithDuration(t, s);//按行切

CCTransitionSplitCols::transitionWithDuration(t, s);//按列切


音乐

#include "SimpleAudioEngine.h"//音乐头文件

using namespace CocosDenshion;//音乐空间命名


//音乐重新播放

SimpleAudioEngine::getInstance()->playBackgroundMusic("Hoaprox - Ngẫu Hứng [mqms].mp3");


//音乐暂停

SimpleAudioEngine::getInstance()->pauseBackgroundMusic();

              

 //音乐继续

SimpleAudioEngine::getInstance()->resumeBackgroundMusic();

//停止背景音乐

SimpleAudioEngine::getInstance()->stopBackgroundMusic();


Text就是我们俗称的Label,就是标签,用来显示文字或者文本的。

    auto label=Text::create“Welcome to Study CocosGUI”“fonts/arial.ttf”30);

label->setColorColor3B25500));

    label->setPositionVec2240270));

this->addChildlabel1);



3Button就是我们俗称的按钮。

我们可以给它添加事件监听,当事件发生时会触发相应的方法。

//图片按钮

auto button=Button::create“button_normal.png”

 //修改成字体按钮

button->setTitleText("+");

button->setTitleFontSize(20)

//点击暂时出现一下的图片     明天测试

button->loadTexturePressed“button_selected.png”); 

button->addClickEventListener[=]Ref* sender{

    log“You Clicked Me Why);});

    button->setPositionVec2400160));

button->setScale0.5);

this->addChildbutton2);




图层变颜色

auto Layer_1 =LayerColor::create(Color4B::RED,480,320);

 this->addChild(Layer_1);



 LoadingBar进度条,我们看到游戏的资源加载界面的进度显示就是通过这个控件完成的。

(人物血量)

auto loadingBar =LoadingBar::create("loadingbar.png");

 loadingBar->setPosition(Vec2(240,280));

        this->addChild(loadingBar,10);

        schedule([=](float dt) {

            static int time=1;

            if (time>=100)

            {

                unschedule("loadingbar");

            }

            time+=10;

            loadingBar->setPercent(time);//百分比


        },1,"loadingbar");


CheckBox(复选框)

 _checkBox2->setSelected(false);//设置当前状态,默认关 false



auto checkBox=CheckBox::create("bg_music_open.png", "bg_music_close.png");

    checkBox->setPosition(Vec2(460,300));

     this->addChild(checkBox,2);

    checkBox->addEventListener([=](Ref*f ,CheckBox::EventType type)

    {

        switch (type)

        {

            case CheckBox::EventType::SELECTED:

            {

                SimpleAudioEngine::getInstance()->pauseBackgroundMusic();

                break;

            }

            case CheckBox::EventType::UNSELECTED:

                SimpleAudioEngine::getInstance()->resumeBackgroundMusic();

                break;

            default:

                break;

        }

    });


3Slider:滑块多用于声音的调节等设置界面。slider->setPercent( int );//slider滑动位置设置,一般写setMaxPercent(10);中的数

auto slider=Slider::create();

slider->setPercent();//slider滑动位置设置



//设置slider背景图片 (红色箭头所指的图)

slider->loadBarTexture("sliderTrack.png"); 

//设置slider滑动按钮图片   粉色箭头所指的图)

    slider->loadSlidBallTextures("sliderThumb.png"); 

//设置slider进度图片   (黄色箭头所指的图)

    slider->loadProgressBarTexture("sliderProgress.png");

    slider->setMaxPercent(10);

    slider->setPosition(Vec2(240,240));

    this->addChild(slider);

    slider->addEventListener([](Ref*sender,Slider::EventType type)

     {

         if (type==Slider::EventType::ON_PERCENTAGE_CHANGED)

         {

             Slider *slider=dynamic_cast<Slider*>(sender);

             int percet=slider->getPercent();

            //设置音量  setBackgroundMusicVolume(percet*0.1);参数最后为0-1

             // setMaxPercent(10);      10 *0.1=1

             SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(percet*0.1);

         }

     });



slider->setEnabled(true );// 默认开   如果false滑块就划不动,禁用了




 PageView:分页显示容器  PageView::自带触摸


PageView* pageView=PageView::create();

    pageView-setcontentsizeSize240.0f130.0f));

    pageView->setPositionVec2120100));

    pageView->removeAllPages();//清除所有页

    int pagecount=4

//添加页面

forint i=0i<pagecount++i

{

Layout* layout=Layout::create();//可以看成模具

1ayout->setContentsizeSize240.0f130.0f));

Imageview* imageView=ImageView::create“pageviewbg.png”);

imageView->setscale9Enabledtrue);

    imageView->setContentSizeSize240130));

    imageView->setPositionVec2layout->getContentSize().width/2.0f,layout->getContentSize() height/2.0f));

    layout->addChildimageView);

Text* label=Text::createStringutils::format“page %d”,(i+1)),“fonts/Marker Felt.ttf”30

1abel->setColorColor3B25500));

    label->setPositionVec2layout->getcontentSize().width /2.0f,layout->getContentSize()。

    height/2.0f));

    1ayout->addChildlabel);

    pageView->insertPagelayout,i//模具     插入页

   }


pageView->scrollToPage(下标); //滑动到该页面


    pageView->getCurPageIndex()//等于该页的下角标  (第3页的下角标为2

    

2ListView:列表容器

ListView* listView = ListView::create();

//类型竖直

    listView->setDirection(ui::ScrollView::Direction::VERTICAL);

    listView->setBounceEnabled(true);//有弹性

//    listView->setBackGroundImage("tabBg1.png");

    listView->setBackGroundImageScale9Enabled(true);

    listView->setContentSize(Size(240, 200));

    

    listView->setAnchorPoint(Vec2(0.5,0.5));

    listView->setPosition(Vec2(340, 160));

    listView->setScrollBarPositionFromCorner(Vec2(7, 7));

    this->addChild(listView,3);

    auto sprite=Sprite::create("StartBG.png");

    this->addChild(sprite,1);

    sprite->setPosition(Vec2(240,160));

    auto sprite1=Sprite::create("tabBg1.png");

    sprite->addChild(sprite1,2);

    sprite1->setContentSize(Size(250, 300));

    sprite1->setPosition(Vec2(340, 160));

    

    string strText[5]={"神圣祝福带来神秘好运","死亡时急速冲刺15","开局急速冲刺2000","保护主角 吸收一次伤害","看不见了QAQ"};

    

    for (int i=0; i<5; ++i)

    {

          Layout*layout=Layout::create();//可以看成模具

        layout->setContentSize(Size(220,50));

        

        Button *button=Button::create(StringUtils::format("c%d.png",i) );

        setAnchorPoint(Vec2(0.5,0.5));

        button->setPosition(Vec2(40,20));

        button->addClickEventListener([=](Ref*f){

            //转场景     入栈 方式

            auto my3=My4::createScene();

            Director::getInstance()->pushScene(my3)

        });

        


        Button *button2=Button::create("buy.png");

        button2->setPosition(Vec2(200,25));

        

        button2->addClickEventListener([=](Ref*f){

            

            auto my3=My4::createScene();

            Director::getInstance()->pushScene(my3);

        });


        string str1=StringUtils::format("d%d.png",i);

        Sprite* btn1=Sprite::create(str1);

        btn1->setPosition(Vec2(110,30));

        Text * text=Text::create(strText[i],"",10);//字体

        text->setAnchorPoint(Vec2(0, 0));

        text->setPosition(Vec2(80, 0));

        text->setColor(Color3B::BLACK);

     

        layout->addChild(btn1);

        layout->addChild(text);

        layout->addChild(button);

        layout->addChild(button2);

        

        //模具   入栈 容器 

        listView->pushBackCustomItem(layout);

               

        listView->insertcustomItem(layout, i);//插入的方式进容器

    


        listView->setItemsMargin(10);//设置间隔

    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值