内容介绍: 自定义事件需要注意: //必须把t的坐标点转成节点坐标点 if(e->getCurrentTarget()->getBoundingBox().containsPoint(e->getCurrentTarget()->convertToNodeSpace(t->getLocation()))){ SimpleAudioEngine::getInstance()->playEffect("eat.wav"); Director::getInstance()->replaceScene(MainScene::createScene()); } 预加载: std::vector<std::string> searchPath; searchPath.push_back("height_864"); CCFileUtils::getInstance()->setSearchPaths(searchPath);//设置项目资源目录 SimpleAudioEngine::getInstance()->preloadBackgroundMusic(FileUtils::getInstance()->fullPathForFilename("sound/music.mp3").c_str() );//预加载背景音乐 SimpleAudioEngine::getInstance()->preloadEffect(FileUtils::getInstance()->fullPathForFilename("sound/dead.wav" ).c_str());//预加载音效 Director::getInstance()->getTextureCache()->addImageAsync("playbg.png", CC_CALLBACK_1(LoadingResScene::loadingCallBack, this));//预先加载纹理图片到缓存中 SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Play.plist");//加载plist文件到精灵缓存中 FileUtils::getInstance()->fullPathForFilename("sound/tip.wav").c_str() //组装成完整的路劲再返回 菜单容器添加: Vector<MenuItem*> menuItemVector; auto item = MenuItemImage::create( "card_1.png", "card_2.png", "card_3.png", CC_CALLBACK_1(LevelSelectPage::menuStartCallback, this)); menuItemVector.pushBack( item ); auto levelMenu = Menu::createWithArray(menuItemVector); menu->alignItemsHorizontally();//菜单水平对齐 ValueMap: ValueMap dict = FileUtils::getInstance()->getValueMapFromFile("a.plist");//把plist文件转成ValueMap resources = dict["resources"].asValueMap(); levelInfo = dict["levelInfo"].asValueMap(); 静态变量一定要赋初值: A* A::a = NULL; 【tiled地图使用2:】 auto map = TMXTiledMap::create("a.tmx"); TMXLayer * layer = map->getLayer("bg"); TMXObjectGroup * objects = map->getObjectGroup("obj"); ValueMap point = objects->getObject(std::to_string(0)); map->getMapSize()是地图有几个块, map->getTileSize()是每一块的大小 layer->getTileGIDAt(Point(1,2));//获得该点上面的GID auto tileTemp = map->getPropertiesForGID(gid).asValueMap();//获得对应GID上的属性字典 【cocos2dx-把触点坐标转换成TieldMap坐标】 cocos2d::CCPoint HelloWorld::covertPointToTiledCoord(cocos2d::CCPoint p) { int x = p.x / mMap->getTileSize().width; int y = ((mMap->getMapSize().height * mMap->getTileSize().height) - p.y) / mMap->getTileSize().height; return ccp(x, y); } 【计算2点之间的距离】 double distance = this->getPosition().getDistance(enemy->sprite->getPosition()); 【使塔跟着敌人旋转】 auto rotateVector = nearestEnemy->sprite->getPosition() - this->getPosition(); auto rotateRadians = rotateVector.getAngle(); //获得弧度 auto rotateDegrees = CC_RADIANS_TO_DEGREES(-1 * rotateRadians); //获得角度 auto speed = 0.5 / M_PI;//获得速度 auto rotateDuration = fabs(rotateRadians * speed); //获得时间 rotateArrow->runAction( Sequence::create(RotateTo::create(rotateDuration, rotateDegrees), CallFunc::create(CC_CALLBACK_0(ArrowTower::shoot, this)), NULL)); 【移除、清除操作】 tips->runAction(Sequence::create(DelayTime::create(0.8f), CallFunc::create(CC_CALLBACK_0(Sprite::removeFromParent, tips)), NULL));//执行完动作后移除自己 this->removeFromParentAndCleanup(true);//在这个节点上所有的动作和回调都会被删除 //移除怪物 nowEnemy->unscheduleAllSelectors(); //不调度所有的调度过的选择器 nowEnemy->stopAllActions(); //停止并且删除所有的动作从活动动作列表中 nowEnemy->removeFromParentAndCleanup(true); GameScene::allEnemy.erase(j); //移除爆炸效果 sp->runAction(Sequence::create( Animate::create(a), CallFuncN::create([](Node * obj){ obj->getParent()->removeFromParentAndCleanup(true); }), NULL)); //加载下一关的操作 levelinf.clear(); //ValueMap allPoint.clear(); //Vector allEnemy.clear(); //Vector allTD.clear(); //Vector GameScene::allBullet.clear();//Vector this->removeAllChildrenWithCleanup(true);//从容器中删除所有的孩子, 取决于cleanup参数同时会清除所有的活动的动作 【总结】 tiled地图文件 引用的图块尽量要用同级目录下的图片,不然移植安卓会出现闪退,找不到文件 【项目总结】 定义个函数类型的变量:(可以用于参数传递) std::function<void ()> callback; 调用的时候callback(); 游戏思想: 1、当精灵向上或者向下移动的时候,在地图检测碰撞的时候,可以取精灵的最上端或者最下端的点来进行验证。 2、设置爆炸效果的时候,动画执行完了,在移除: auto sequence = RepeatForever::create(Sequence::create(animate,CallFunc::create([this,s](){_mapLayer->removeChild(s,true);}),NULL)); s->runAction(sequence); 【cocostudio】 项目使用方法: 添加现有项目: cocos2dextensionsproj.win32 cocos2dcocosuiproj.win32 cocos2dcocoseditor-supportcocostudioproj.win32 然后选中项目右键,添加引用到项目中。 然后选中项目右键属性,选中c++ 添加附加目录:cocos2dcocos的目录和cocos2d #include "cocos2d.h" #include "extensions/cocos-ext.h" #include "ui/CocosGUI.h" USING_NS_CC; using namespace ui; UI 【Button的使用:】 Button * button = Button::create("默认状态的图片","点击的时候的图片"); button->setPosition(ccp(100,100)); this->addChild(button); button->addTouchEventListener(this,toucheventselector(HelloWorld::touchEvent(); button->setPressedActionEnabled(true);//点击的时候放大 void HelloWord::touchEvent(Ref *pSender,TouchEventType type){ switch(type) { case TOUCH_EVENT_BEGAN: break; case TOUCH_EVENT_MOVED: break; case TOUCH_EVENT_ENDED: break; case TOUCH_EVENT_CANCELED: //点击后在外面取消触发 break; default: break; } } 【CheckBox 复选框使用:】 CheckBox *checkBox = CheckBox::create("缺省情况下图","被按下的图","被激活的图","缺省禁用的状态","缺省禁用激活状态"); this->addChild(checkBox); checkBox->addEventListenerCheckBox(this,checkboxselectedeventselector(Helloworld::selectEvent)); void HelloWorld::selectedEvent(Ref * pSender,CheckBoxEventType type){ switch(type){ case CHECKBOX_STATE_EVENT_SELECTED: //选中状态下 break; case CHECKBOX_STATE_EVENT_UNSELECTED: //取消状态下 break; } } 【Slider滑块组件:】 Slider *slider = Slider::create(); slider->loadBarTexture("背景"); slider->loadSlidBallTextures("缺省状态下控制图片","缺省状态下激活状态的图片"); slider->loadProgressBarTexture("进度的图片"); slider->setPosition(ccp(100,100)); slider->addEventListenerSlider(this,slidepercentchangedselector(Helloworld::sliderEvent)); void Helloworld::slideEvent(Ref *s,SliderEventType type){ if(type == SLIDER_PRECENTCHANGED){ Slider * slider = (Slider *)s; int p = slider->getPercent();//获得滑块的数值 } } 【ImageView图像组件:】 ImageView *img = ImageView::create("图片"); this->addChild(img); img->setPosition(Point(100,100)); img->setScale9Enabled(true);//启动缩放 img->setSize(Size(300,60));//可以设置图片宽高 【LoadingBar 进度条:】 LoadingBar *l = LoadingBar::create("进度的图片"); l->setPosition(Point(100,100)); this->addChild(l); l->setDirection(LoadingBarTypeRight);//让进度条向右递增 count = 0; this->schedule(schedule_selector(Helloworld::loadings),0.1); void Helloworld::loadings(float f){ LoadingBar * load = (LoadingBar *)this->getChildByTag(100); count ++; if(count>=100){count = 0;} load->setPercent(count); } 【添加图片文字】 TextAtlas *t = TextAtlas::create("显示的文字","纹理文字图片","裁剪的宽度","裁剪的高度","从哪里开始 如0"); t->setPosition(Point(100,100)); this->addChild(t); Text *text = Text::create("文本内容","字体",32); this->addChild(text); text->setSize(Size(200,300));//设置文本狂大小 text->ignoreContentAdaptWithSize(false);//设置自动换行 text->setTextHorisontalAlignment(TextHAlignment::CENTER);//设置文本居中 TextBMFont *mb = TextBMFont::create("显示的内容","aaa.fnt"); mb->setPosition(Point(100,100)); 【文本输入框】 TextField * t = TextField::create("请输入文字","黑体",20); t->sePosition(Point(100,100)); this->addChild(t); t->setMaxLengthEnabeld(true); t->setMaxLength(3);//设置最多输入的长度 t->getStringValue();//获取输入的字符信息 t->setPasswordEnabled(true);//设置密码框 t->setPasswordStyleText("*");//设置密码字符 t->addEventListenerTextField(this,textfieldeventselector(Hello::textFiledEvent)); void Hello::textFiledEvent(Ref *r,TextFiledEventType type){ switch(type){ case TEXTFIELD_EVENT_ATTACH_WITH_IME: break; ... } } 【Layout布局组件】 Layout *l = Layout::create(); l->setSize(Size(200,200)); l->setBackGroundColorType(LAYOUT_COLOR_GRADIENT);// 背景渐变 l->setBackGroundColor(Color3B::GREEN);//背景颜色 l->setBackGroundImage("背景图片"); l->setLayoutType(LAYOUT_LINBAR_VERTICAL);//垂直对其 在Layout中添加组件 Button *b = Button::create(); l->addChild(b); 【scrollView滚动视图】 ScrollView * scrollView = ScrollView::create(); scrollView->setSize(Size(280.0f,150.f)); scrollView->setPosition(100,100); this->addChild(scrollView); scrollView->setInnerContainerSize(Size(280,1000)); scrollView->addChild(button);//添加一个button到视图中 scrollView->setBounceEnabled(true);//反弹 scrollView->setBackGroundImage("xxx.png");//设置背景图 scrollView->setDirection(SCROLLVIEW_DIR_BOTH);// 【pageView页面翻转】 PageView * p = PageView::create(); p->setSize(Size(100,300)); for(int i = 0; i < 3; i++){ Layout * layout = Layout::create(); layout->setSize(Size(200,130)); ImageView *img = ImageView::create("xxxx.png"); img->setSize(Size(200,130)); layout->addChild(img); p->addPage(layout); } pageView->addEventListenerPageView(this,pagevieweventselector(Hello::pageTest)); void Hello::pageTest(Ref *s,PageViewEventType type){ switch(type){ case PAGEVIEW_EVENT_TURNING: { PageView * p = (PageView *)(s); int page = p->getCurPageIndex()+1;//获得当前的页码 } } } 【listView列表视图】 ListView *l = ListView::create(); l->setDirection(SCROLLVIEW_DIR_VERTICAL); l->setTouchEnabled(true);//可以触摸 l->setBounceEnabled(true);//可以反弹 l->setBackGroundImage("xxx.png");//设置背景图 l->setSize(Size(200,100)); l->setPosition(100,100); l->addEventLisenerListView(this,listvieweventselector(Hello::listtest)); Layout *default_item = Layout::create(); Button * button = Button::create("",""); default_item ->addChild(button); l->setItemModel(default_item);//设置一个默认模型 for(int i = 0; i <5 ; i ++){ l->pushBackDefaultImte();//把模型放到listView 显示5行默认模型 } for(int i = 0; i <5 ; i ++){ l->insetDefaultImte();//把模型放到listView 显示5行默认模型 } l->removeLastItem(); l->removeItem(1); l->addEventListenerListView(this,listvieweventselector(Hello:listviewtest)); void Hello:listviewtest(Ref *s,ListViewEventType type){ switch(type){ case LISTVIEW_ONSELECTEDITEM_START: ListView *l = (ListView *)s; l->getCurSelectedIndex();//获得当前选中的条目 break; } } 【RichText 复文本,包含图片 文本 动画】 RichTest *t = RichText::create(); t->ignoreContentAdapWithSize(false);//自动换行 t->setSize(Size(100,100)); RichElementText *r1 = RichElementText::create(1,Color3B::WHITE,255,"This color is white","Helventica",10); RichElementText *r2 = RichElementText::create(1,Color3B::WHITE,255,"This color is white","Helventica",10); RichElementImage *img = RichElementImage::create(6,Color::WHITE,255,"fdfsd.png"); t->pushBackElement(r1); t->pushBackElement(r2); t->pushBackElement(img); this->addChild(t); 【用cocostadio ui编辑器】 #include "cocos2d.h" #include "uiCocosGUI.h" #include "cocostudio/Cocostudio.h" USING_NS_CC; using namespace ui; //加载UI编辑器编辑的UI布局 Layout *l = static_cast<Layout *>(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("NewUi_1.json")); this->addChild(l); //获取布局中的对象 Button *button1 = static_cast<Button *>(Helper::seekWidgetByName(l,"btn01"));//通过按钮的名称获得按钮 button1->addTouchEventListener(this,toucheventselector(HelloWorld::menuCloseCallback));//添加事件监听 void HelloWorld::menuCloseCallback(Ref* sender,TouchEventType type) { switch(type) { case Widget::TouchEventType::ENDED: log(">>>"); } } 【box2d】 世界: 刚体:静态刚体,动态刚体,平行刚体(像电梯,一直运动下去),由形状和夹具组成的 形状:圆形、多边形 夹具:像人的各个部位都是一个家具,组成的形状物体 关节: 线关节: 菱镜关节: 旋转的关节: 滑轮关节: 齿轮关节: 鼠标关节: 碰撞点: //获得所有body对象 for(b2Body *b = m_world->getBodyList();b;b=b->getNext()) { //千万不要在这里直接删除b指向的body对象,完成循环再删除 } //获得所有夹具 for(b2Join *j = m_world->getJoinList();j;j=j->getNext()) { //千万不要在这里直接删除j指向的夹具对象,完成循环再删除 } //获得所有碰撞点 for(b2Join *j = m_world->getContactList();j;j=j->getNext()) { //千万不要在这里直接删除j指向的碰撞点对象,完成循环再删除 } CCSpriteBatchNode * batch = CCSpriteBatchNode::create("batch.png"); Texture2D *bs = batch->getTextture(); CCSprite* testIcon = CCSprite::createWithTexture( bs); batch->addChild(testIcon); addChild(batch); getPhysicsBody()->setDynamic(false);//设置成不是动态物体,不受力影响 getPhysicsBody()->setRotationEnable(false);//设置成不在旋转 getPhysicsBody()->setVelocity(Vec2(0,100));//设置速度 编译成功链接失败: 1没有重写需要重写的方法 2有的方法没有实现,只是定义