• QQ
  • nahooten@sina.com
  • 常州市九洲新世界花苑15-2

游戏开发

Cocos2Dx 少许残存的API

原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2019/0920/650.html

 新建常州游戏开发培训名目:
 
cocos new -p xxx.xxx.xxx -l cpp xxx -d
 
xxx是自定义名字
 
-d为指定目次不指定该号令行参数,默认为目前目次
 
 
 
该漫笔用来纪录遇到的噜苏的API,以加深印象,以后找起来也利便。
 
场景:
 
Director::getInstance()->replaceScene(scene);// 切换场景
 
Director::getInstance()->replaceScene(TransitionSlideInt::create(3.0f,scene));//带特效切换场景
 
Director::getInstance()->pushScene(scene)//push 和pop场景不会造成旧场景内存开释
 
 
 
控件:
 
Label* label = Label::create("hello","Arial",40);//label表现的字符,字体,字号
 
label->setPosition(Point(300,300));也可应用重载的方法,参数为x和y坐标
 
MenuItemLabel1* pLabelItem = MenuItemLabel1::create(label);//以label作为菜单项
 
Menu* pMenu = Menu::create(pLabelItem,NULL);// 把才菜单项加入菜单
 
pMenu->alignItemsVertivslly();//垂直自动排列
 
addchild(pMenu);//菜单加入场景即可
 
controlButton* controlBtn =ControlButton::create(label,sprite);          //按钮控件类
 
controlBtn->setBackgroundSpriteForState(sprite,Control::State::HIGH_LIGHTED);//配置按下图片
 
controlBtn->setPreferredSize(Size(300,100));//配置固定大小,若图片超过该大小则变大
 
 
 
 
 
回调函数://传递一个函数,并且在某时候挪用它
 
HelloWorld中的关闭按钮回调函数:
 
复制代码
 void menuCloseCallback(cocos2d::Ref* pSender); //头文件中的说明
   auto closeItem = MenuItemImage::create(          //cpp文件中的挪用
                                          "CloseNormal.png",                                          "CloseSelected.png",
                            CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));大概
   auto closeItem = MenuItemImage::create(         //create的一另一个重载方法
                                           "CloseNormal.png",                                           "CloseSelected.png",                                            this,
                                 menu_selector(Helloworld::menuCloseCallback));
复制代码
 
 
 
 
监听器://一直监听,一旦产生某事件就挪用
 
复制代码
void onClick(cocos2d::Ref *psender,cocos2d::ui::TouchEventType type);//手机App外包头文件中的说明rightButton->addTouchEventListener(this,toucheventselector(MyHelloWorld::onClick));//cpp文件中挪用void MyHelloWorld::onClick(Ref* pSender,TouchEventType type){ //cpp文件中的实现
    switch (type) {        case cocos2d::ui::TOUCH_EVENT_ENDED: //松开触发
            if(picture->isVisible())
               picture->setVisible(false);            else
                picture->setVisible(true);    
            healthBar->setPercent(healthBar->getPercent() - 1);//血条降落
            break;        case cocos2d::ui::TOUCH_EVENT_BEGAN: //按下后触发
            break;        case cocos2d::ui::TOUCH_EVENT_MOVED: //按下后挪动触发
            break;        case cocos2d::ui::TOUCH_EVENT_CANCELED: //因为分外环境中缀触发
            break;         
        default:            break;
    }
}
复制代码
 触摸监听器相应触摸事件:
 
复制代码
 auto listener =EventListenerTouchOneByOne::create();//单点触摸
    listener->onToucheBegan=[&](Touch* touch,Event* event){        //Point pos1 = touch->getLocation() //获取基于3D的touch坐标
        Point pos2 = touch->getLocationInView() //获取基于2D的touch坐标
        Point pos3 = Director::getInstance()->convertToGL(pos2) //获取基于cocos2d的touch坐标
        auto target = static_cast<Sprite*>(event->getCurrentTarget());//获取注册监听器时绑定的精灵
        if(target->getBoundingBox().containsPoint(pos3)){//校验出点是否在精灵内
         Log("Touch the Sprite!");
        }
        };
    listener->onTouchMoved=[&](Touch* touch,Event* event){
            Point pos2 = touch->getLocationInView() //获取基于2D的touch坐标
            Log("Position is %f,%f",pos2.x,pos2.y);    //挪动时输出坐标    };
    listener->onTouchEnded=[&](Touch* touch,Event* event);
     Log("onTouchEnd!");
    };
      listener->setSwallowTouches(true);//若App开发培训两个精灵重复,则惟有上头的相应事件
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, sprite);//注册监听事件,绑定精灵,留意为第二个精灵注册监听器时需求listener->clone()来取代listener
复制代码
复制代码
 auto listener =EventListenerTouchAllAtOnce::create();//多点触摸
    listener->onTouchesBegan=[&](const std::vector<Touch*>& touches,Event* events){
        auto logtext = (Label*)this->getChildByTag(1);        int num = touches.size;
        logtext->setString(Value(num).asString+"Touches");
        };
    listener->onTouchesMoved=[&](const std::vector<Touch*>& touches,Event* events){
        auto logtext = (Label*)this->getChildByTag(2);
        std::string text = "";        for(auto &touch:touches){//遍历每一个触摸
            auto location = touch->getLocation();
            text += "[touchID" + Value(touch->getID()).asString() + "],"
        }
        logtext -> setString(text);
    };
    listener->onTouchesEnded=[&](const std::vector<Touch*>& touches,Event* events){
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);//注册监听事件,绑定精灵
复制代码
 
 
 
 
 
 
 
 
应用Value进行范例转换:
 
int a = Value("1234").asInt();
 
float b = Value("12.45").asFloat();
 
string s = Value(123.4f).asString();//要是在log输出则要应用%s,并且在asString()后加c_str();
 
 
 
播放声响:
 
#include “simpleAudioEngine.h”
 
CocosDenshion::SimpleAudioEngine::getInstance()->playBackGroundMusic("xxxx.mp3",true);//文件名,是否轮回.
 
该方法只适用播放较长的音乐如BGM,若是急促的音效应该应用:
 
CocosDenshion::SimpleAudioEngine::getInstance()->playBacEffect("xxxx.wav")
 
 
 
Scale9Sprite:可拉伸且不失真的图片
 
#include "cocos-ext.h"
 
using namespace cocos2d::extension;
 
Scale9Sprite* nineGirl1 = Scale9Sprite::create("CloseNormal.png");
 
nineGirl->setContentSize(Size(200,100));
 
 
 
CocosStudio:
 
#include "editor-support/cocostudio/CocoStudio.h"
 
#include "ui/CocosGUI.h"
 
using namespace cocos2d::ui;
 
using namespace cocostudio;
 
应用cocosStudio实现UI并导出为csb文件后(留意资源要一路导出)
 
auto UI = CSLoader::createNode("MainScene.csb");//加载csb文件
 
UI->setPosition(Point(0,0));
 
Button* rightButton = (Button*)UI->getChildByName("Button_1");//凭据控件名获取控件
 
 
 
 动作:
 
MoveTo* m_move = MoveTo::create(0.9f,Point(200,100));//统统挪动 MoveBy相对挪动
 
ScaleTo* m_scale = ScaleTo::create(3.0f,2.0f,2.0f);//统统缩放 ScaleBy相对缩放 参数为 光阴,x,y
 
Blink* blink = Blink::create(3.0f,3);//闪灼 参数为连接光阴和次数
 
JumpTo* m_jump = JumpTp::create(3.0f,Point(50,1),100,1);//统统跨越 JumpBy相对跨越,参数为光阴,目标地,高度,次数
 
 ccBezierConfig bezier;//贝塞尔曲线
 
bezier.controlPoint_1 = Point(100,0);//波谷方向值
 
bezier.controlPoint_2 = Point(200,250); //波峰方向值
 
bezier.endPosition = Point(300,50);  //终点
 
BezierTo* bezierTo = BezierTo::create(4.0f,bezier);
 
RepeatForever* repeatAction = RepeatForever::create(m_jump);
 
Repeat* repeatAction2 = Repeat::create(m_jump,3);//指定重复次数
 
Action* actions1 = Spawn::create(m_move,m_scale,blink,NULL);//同时播放动作
 
Action* actions2 = Sequence::create(m_move,m_scale,blink,NULL);//挨次播放动作
 
sprite->runAction(actions2);
 
sprite->stopAllActions(); //休止所有动作
 
auto callbackFunc = [&](){//lambda函数是一个匿名函数[]表示要开始一个lambda函数,
  doSomeThing();             //()内是函数参数};//[&]表示可以以援用的方法应用外部变量,[=]表示以复制的方法应用外部变量CallFunc* callFunc = CallFunc::create(callbackFunc);//CallFunc是一个隐形的动作,其用途相似于回调函数,应用lambda函数作为回调函数
 
 
上头常州网站开发培训是动作分类图,分为登时执行的动作,如show()另有有连接光阴的动作,如MoveTo()。
 
 
 
获取随机数:
 
CCRANDOM_0_1() //获取0到1之间的随机数
 
 
 
按时器:
 
virtual void update(float dt) //需求重写update方法
 
this->scheduleUpdate(); //启动按时器,update每帧挪用一次
 
 
 
 
 
碰撞检验:
 
Rect entiryRect = Object->getBoundingBox();//若游戏工具没有秉承Sprite,而是把Sprite作为一个属性,则需求从新配置
 
Point pos = getPosition();                             //Object的大小,用setContentSize . 而后把绑定在Object上的精灵位置
 
return entityRect.containsPoint(pos);             //挪动到Size/2的位置
 
 
 
 
 
配置渲染挨次:参数越大越在表面(晚绘制) 
 
sprite->setGlobalZOrder() //可以对于差别层决意绘制挨次
 
sprite->setLocalZOrder() //对于统一节点的子节点决意绘制挨次
 
sprite->setOrderOfArrival()// 在LocalZOrder相像时决意绘制先后挨次
 
 
 
绘制大批精灵
 
Cocos2dx 3.0 应用了auto-batching来办理大批绘制精灵的环境
 
cocos会自动应用auto-batching,不过需求满足以下条件:
 
1.绘制的精灵应用哪一个统一张纹理,相像的材质和混合功效.
 
2.绘制是连续的。(是否连续受渲染挨次影响)
 
3.不把精灵增加到SpriteBatchNode(2.0期间处分大批绘制的方法).
 
 
 
应用TexturePacker打包图片:
 
配置参数: Dithering: 抖动表现,可以缓和图像失真
 
               Size constrains: 打包图为2的次方,如125*150,150>128,以是会打包成128*256
 
               Allow rotation:容许图片扭转来放更多图片,不影响读取时的表现
 
               Trim: 出去图片的透明片面节减空间,并且不会使对齐无效
 
把多张图放入TexturePacker打包成一张后,若何读取呢?
 
复制代码
SpriteFrameCache* frameCache = SpriteFrameCache::getInstance();
    frameCache->addSpriteFramesWithFile("move.plist","move.png");
    Sprite* sprite1 = Sprite::createWithSpriteFrameName("001.png");//应用单张图片的名字读取即可
    Sprite* sprite2 = Sprite::createWithSpriteFrameName("003.png");
    sprite2->setTextureRect(Rect(0, 0, 150, 100));//截取纹理的片面    //setPosition.....
复制代码
建立动画:动画也是action,用runAction播放即可。
 
应用未打包的图片建立动画:这种方法需求手动指定SpriteFrame大小
 
复制代码
cocos2d::Animate* HelloWorld::createAnimation1(){    int iFrameNum = 8;
    Vector<SpriteFrame*> frames;
    SpriteFrame* frame = NULL;    for(int i =0; i<iFrameNum ;i++){
        frame = SpriteFrame::create(StringUtils::format("00%d.png",1), Rect(0, 0, 150, 150));
        frames.pushBack(frame);
    }
    Animation *animation = Animation::createWithSpriteFrames(frames);
    animation->setDelayPerUnit(0.01);//每张播放间隙
    animation->setLoops(-1);
    Animate* action = Animate::create(animation);    return action;
}
复制代码
应用企业培训打包的图片建立动画:
 
复制代码
cocos2d::Animate* HelloWorld::createAnimation2(){
    SpriteFrameCache *framecache = SpriteFrameCache::getInstance();
    framecache->addSpriteFramesWithFile("move.plist", "move.png");   
    int iFrameNum = 8;
    Vector<SpriteFrame*> frames;
    SpriteFrame* frame = NULL;    for(int i =1; i<=iFrameNum ;i++){
        log(i);        //log(StringUtils::format("00%d.png",i));
        frame = framecache->getSpriteFrameByName(StringUtils::format("00%d.png",i));
        frames.pushBack(frame);
    }
    Animation *animation = Animation::createWithSpriteFrames(frames);
    animation->setDelayPerUnit(0.1);
    animation->setLoops(-1);
    Animate* action = Animate::create(animation);    return action;
}
复制代码
 

上篇:上一篇:ocos2d-x中文乱码问题的几种办法
下篇:下一篇:Unity5资源经管AssetBundle—更新完成