Cocos2dx3.0 Super Mario Development Notes (1) -- Use of loadingbar and pageview

Source: Internet
Author: User

After completing the first project of the cocos2dx course, I chose super Mary. It can be said that you have your own ideas, simple but not simple.

I spent a day upgrading the super Mary source code of Version 2.1 to version 3.0, modifying, modifying, deleting, and referring to the source code. Although I don't know much about it, the upgrade was successful and the game was playing normally.

Based on the idea of not writing code for the game, I listed the knowledge points that can be used by the game. Three methods of Data Persistence: loading page, tmx map resolution, cocosstudio scenario, screen adaptation, how to choose a level, and code structure optimization (various types of abstract inheritance ), after the basic functions are available, you can design your own abnormal checkpoints.


In the past two days, the loading interface and the main interface are implemented for all scenarios and selection scenarios.

The effect is as follows: GIF:



In the loading scenario, the progress bar is super. For a simple game like Mary, there is no need to pre-load too many things, or there is no need for a heavy interaction like loading. No way. Be familiar with some methods and learn. Don't be too real. The progress bar of the scenario uses progresstimer. If we use the scenario created by cocosstudio, we will use the tool. Set a progress bar member variable, and then:
Loadprogress = progresstimer: Create (sprite: Create ("image/loadingbar.png"); loadprogress-> setbarchangerate (point (1, 0 )); // set loadprogress-> settype (progresstimer: Type: bar); // set loadprogress-> setmidpoint (point (0, 1); // set the movement direction of the progress to loadprogress-> setposition (visiblesize. width/2, visiblesize. height/2); loadprogress-> setpercentage (progresspercent); this-> addchild (loadprogress );

To adjust the progress bar, you only need to implement it in the callback function for Asynchronously loading resources. Other effects such as loading can also be implemented in the scenario of loading. asynchronous loading does not cause too many lag Effects on the interface, unless the mobile phone is too bad ..
There are three types of cache for asynchronous resource loading: texturecache, spriteframecache, and animationcache. We need to pre-load different resources as needed during loading. Then process the progress bar in the callback function. I use the simplest texturecache to log on to loading. Add the preloadresource function in init. This function will be executed directly without waiting for any results. Then the resource is loaded in the background.
Void loadingscene: preloadresource () {// write test separately here. If it is determined that it is a scenario, directly use plist to load STD: String resoucemain = "image/mainscene /"; float COUNT = 20; // load a total of 17 everyadd = 100/count; ctor: getinstance ()-> gettexturecache ()-> addimageasync (resoucemain + "about_normal.png ", callback (loadingscene: loadingcallback, this); ctor: getinstance ()-> gettexturecache ()-> addimageasync (resoucemain + "Callback", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache ()-> addimageasync (resoucemain + "backa.png", cc_callback_1 (loadingscene: loadingcallback, this); Director :: getinstance ()-> gettexturecache ()-> addimageasync (resoucemain + "backb.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "background.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "bg.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "music_off.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "music_on.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "quitgame_normal.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "quitgame_select.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "set_music.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "setting_n.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "setting_s.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "startgame_normal.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "startgame_select.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "wxb.jpg", cc_callback_1 (loadingscene: loadingcallback, this); ctor: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "zhy.jpg", cc_callback_1 (loadingscene: loadingcallback, this); ctor: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "sound_effect_off.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "sound_effect_on.png", cc_callback_1 (loadingscene: loadingcallback, this); Director: getinstance ()-> gettexturecache () -> addimageasync (resoucemain + "switchbg.png", cc_callback_1 (loadingscene: loadingcallback, this ));}

In the callback function:
Void loadingscene: loadingcallback (texture2d *) {progessadd ();} void loadingscene: progessadd () {progresspercent + = everyadd; If (Progress <everyadd) {progresspercent = 100; auto scene = mainscene: createscene (); ctor: getinstance ()-> replacescene (transitionfade: Create (1, Scene);} percentlabel-> setstring (stringutils :: format ("% d", INT (progresspercent); // update the percentlabel value loadprogress-> setpercentage (progresspercent );}
Switch the scenario from loading to 100%. Not many progress bars of resources do not move forward with + 1, and there is no technical implementation method here. I hope you can tell me when you have made optimization. Thank you very much for your progress ~
The main game scenario is skipped here, and you can see the source code. It's just a simple background and two menus.
This article focuses on the selection of checkpoints. Super Mary has eight levels. You can select the corresponding level for the game. Here, we implement the function similar to defending the radish level switch. Drag left and right to select the level and click to play the game. There are three ways to achieve this: first, create a layer and add eight genie horizontally. Implement touch events, and move the left and right touch to move the layer. After the touch ends, adjust the position of the layer based on the drag position (using the moveTo animation ). The mechanism of this method is simple, but it is complicated to write. Type 2: I used tableview. I didn't understand the usage of tableview at the beginning. I failed to try it. Tableview can create a series of small units horizontally or vertically, and you can set the interval between these units. I thought about it. It is especially suitable for ranking. I don't know how well scroll performs ranking.
The disadvantage of tableview is that when the drag ends, it determines the unit to stop based on the touch inertia, which does not meet our expectations.
Error parsing using tabelview:Import library libextensions add header file # include "cocos-ext.h" cocos2dx cannot open include file: "extensions/extensionmacros. h ": no such file or directory (.. \ Classes \ selectlevel indicates that $ (engineroot) is not introduced to the appended include directory (for how to add the directory, refer to my blog: Click to open the link) usage: Add in init, do not discard the proxy method setdelegate, or you will find no response:
tableView = TableView::create(this, Size(spWidth, spHeight));tableView->setDirection(ScrollView::Direction::HORIZONTAL);tableView->setPosition(Point((winSize.width - spWidth)/2, (winSize.height-spHeight)/2));tableView->setDelegate(this);this->addChild(tableView);tableView->reloadData();
The six callback functions that must be implemented, two of which are scroll's declaration of {} in the. h file.
void SelectLevel::tableCellTouched(TableView* table, TableViewCell* cell){CCLOG("cell touched at index: %ld", cell->getIdx());}Size SelectLevel::tableCellSizeForIndex(TableView *table, ssize_t idx){return Director::getInstance()->getVisibleSize();}TableViewCell* SelectLevel::tableCellAtIndex(TableView *table, ssize_t idx){auto string = String::createWithFormat("%ld", idx+1);TableViewCell *cell = table->dequeueCell();if (!cell) {cell = new TableViewCell();cell->autorelease();auto sprite = Sprite::create(StringUtils::format("image/level/select%d.jpg", idx));sprite->setAnchorPoint(Point::ZERO);sprite->setPosition(Point(0, 0));cell->addChild(sprite);auto label = Label::createWithSystemFont(string->getCString(), "Helvetica", 20.0);label->setPosition(Point::ZERO);label->setAnchorPoint(Point::ZERO);label->setTag(123);cell->addChild(label);}else{auto label = (Label*)cell->getChildByTag(123);label->setString(string->getCString());}return cell;}ssize_t SelectLevel::numberOfCellsInTableView(TableView *table){return Global::getInstance()->getTotalLevels();}



Third: pageview. There are examples in the official demo. In extensions-> bottom-> GUI edito, the first thing I see is that this effect is what I want (at least similar, we can change it ). It is also easy to implement according to the demo. Note: pageview-> addeventlistenerpageview (this, pagevieweventselector (selectlevel: pageviewevent ));
The Declaration of the callback function pageviewevent must be used:
void SelectLevel::pageViewEvent(Ref *pSender, PageViewEventType type){}
Never use:
void SelectLevel::pageViewEvent(Ref *pSender){}
No error is reported for compiling later, but an error is reported during running.
The implementation of pagelist is as follows:
    pageView = PageView::create();pageView->setSize(Size(winSize.width, winSize.height));pageView->setPosition(Point(0,0));for (int i = 1; i < Global::getInstance()->getTotalLevels(); i++){Layout* layout = Layout::create();layout->setSize(Size(winSize.width, winSize.height));ImageView* imageView = ImageView::create(StringUtils::format("image/level/select%d.jpg", i));imageView->setScale9Enabled(true);imageView->setSize(Size(spWidth, spHeight));imageView->setPosition(Point(layout->getSize().width / 2.0f, layout->getSize().height / 2.0f));layout->addChild(imageView);Text* label = Text::create(StringUtils::format("page %d", i), "fonts/Marker Felt.ttf", 30);label->setColor(Color3B(192, 192, 192));label->setPosition(Point(layout->getSize().width / 2.0f, layout->getSize().height / 2.0f));layout->addChild(label);pageView->addPage(layout);}pageView->addEventListenerPageView(this, pagevieweventselector(SelectLevel::pageViewEvent));this->addChild(pageView);

In this way, we have implemented drag-and-drop selection. Now we need to click to start the game. There is another problem here. The callback function of pageview calls back every time you touch the end, so we cannot perform scenario Switching Based on its callback function. I want to add a touch event on the current layer to determine the game to start. The result shows that pageview intercepts the touch callback event. No way. I added a transparent layer on the pageview to process the touch time and start the game. First, add the transparent layer:
auto layerr = Layer::create();layerr->setContentSize(Size(spWidth, spHeight));layerr->setPosition(size.width/2, size.height/2);layerr->setZOrder(111);this->addChild(layerr);auto listenTouch = EventListenerTouchOneByOne::create();listenTouch->onTouchBegan = CC_CALLBACK_2(SelectLevel::onTouchBegan, this);//listenTouch->onTouchMoved = CC_CALLBACK_2(SelectLevel::onTouchMoved, this);listenTouch->onTouchEnded = CC_CALLBACK_2(SelectLevel::onTouchEnded, this);//listenTouch->onTouchCancelled = CC_CALLBACK_2(SelectLevel::onTouchCancelled, this);Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listenTouch, layerr);
It is actually a good touch callback: You need to determine when to switch the scenario. Do not switch when you touch the outside area of pageview, and do not switch when you move pageview more than 5 pixels.
Bool selectlevel: ontouchbegan (touch * touch, event * event) {clickbeginpoint = touch-> getlocation (); Return true;} void selectlevel: ontouchended (touch * touch, event * event) {int dragdistance = ABS (touch-> getlocation (). x-clickbeginpoint. x); // if you click more than 5 pixels to switch the scenario if (dragdistance <5) {rect layerrect = rect (winsize. width-spwidth)/2, (winsize. height-spheight)/2, spwidth, spheight); If (layerrect. containspoint (touch-> getlocation () {// The Int level to be switched over = pageview-> getcurpageindex () + 1 ;}}}

Here, pageview selects and starts the corresponding level game.

The tmx map will be parsed tomorrow. If you need the source code, you can add an email to [email protected] Or qq179261480. After the code is completed, the entire code is shared.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.