Cocos2d-x 3.0 game instance learning notes "tower guard" Step 2 --- Editor (1) -- touch add point

Source: Internet
Author: User
Tags addchild

/* Description:

** 1. This game instance is the last game on the cocos2d-x game development journey, which is rewritten and noted down here with 3.0

** 2. I have also asked me about wood. He said: write the code casually. First, do not copy the code completely. Second, it means learning notes.-good guys.

** 3. Here With cocos2d-x 3.0 version number rewriting, A lot of places are different, but from the rewriting process is also very good to learn the cocos2d-x

*/

* ** All the corresponding code and resources used in each step are packaged at the end.

* ** To avoid code overhead, the code in each step is marked. At first glance, the code is implemented in the first step to avoid errors and cannot be changed back (if not, git should be used again ?)

* ** Based on the design idea (well, the name is too tall. The reality is this step to do) first self-realization-cocos2d-x is so, the same function has a lot of different implementation methods; first self-toss is quite good.

* ** For the convenience of porting to the mobile phone, the android compiler is compiled for each step. Since the code can be compiled in Win32 many times, compilation will fail, the given code will be given after the trial.

Note content:

1. Design Ideas & attention

2,

3. Check the code for the trailing design ideas

4. preview the knowledge in the next section

I. design ideas and attention

Step by step

(1) In response to the edit button in mainscene, A poseditorscene is required. However, this scene requires more tasks than the timeline. Therefore, scene is extracted separately and then various layers are added to it.

(2) Let's get a getbacklayer that can be 10 thousand first. Why is it omnipotent? The function of this layer is very easy. There is a button, back; with this button, you can return to mainscene wherever you are. After you start the game, you select the level and find that you want to re-edit the monster route, and you will be back. You do not want to play back in the game. In the editing scenario, are you ready to edit it and want to try again? Back. Now, you can try again.

(3) Let's have a poseditorlayer. We will edit the monster route and gun position on this layer. Then, through the screen touch, we need to give this layer a touch event to add a pos, you can also give it a try in touch events.

(4) Since the touch is added to a vertex, we need posbase to inherit from the node, and then rewrite the draw function. After the screen is touched, add the vertex, Which is draw. However, here we need to note that we have two points: tower and monster. The method of wood is to extract a posbase base class and then inherit it separately. In this case, it is convenient to expand in the future. If there is another point, it can be inherited in the same way. I can see that the functions of the two points are almost the same, so I am too lazy to use posbase, then, an enumeration class is used to distinguish whether the current vertex is tower or monster.

(5) It should be noted that enumeration classes are necessary. In the editing layer, you also need to change different types for editing.

(6) The buttons in the getbacklayer use the extension library, and some problems need to be solved-simpler than the extension library.

(7) If we rewrite the draw function here, we don't know why it will be blocked by the background. n methods have been tried by many Parties. Finally, we think about it smartly and set the transparency of the background image; I saw it again. I only asked the old brother of wood. The solution he tried was: the draw function was first painted, so the posbase would not be added to the background layer, only one layer can be detached;

(8) The editor has more content than the idea. This step is provided here first.

Ii. Last

Click any position on the screen and a tower is displayed. At the same time, there is an enumeration member in the poseditorlayer, Which is initialized as a tower and can also be used as a monster benchmark.


Iii. Code-based design ideas

First, poseditorscene. h

class PosEditorScene{public:static Scene* createScene();};/**/

Yes, it's that simple. We only need to obtain a scene here. Other layers are in createscene.

. Cpp

Scene* PosEditorScene::createScene(){Scene* scene = Scene::create();//auto posEditorLayer = PosEditorLayer::create();//scene->addChild(posEditorLayer);auto getBackLayer = GetBackLayer::create();scene->addChild(getBackLayer);return scene;}
Then let's take a look at getbacklayer. h.

#include "cocos2d.h"#include "cocos-ext.h"USING_NS_CC;USING_NS_CC_EXT;class GetBackLayer : public Layer{public:CREATE_FUNC(GetBackLayer);virtual bool init();private:void getBack(Ref* pSender, Control::EventType event);};/**/

Create_func is actually a macro-defined create function. When a layer is added to scene, create will call the init function of the layer. Here we only need to implement the virtual bool init function.

. Cpp

bool GetBackLayer::init(){auto visibleSize = Director::getInstance()->getVisibleSize();auto btnTitle = Label::create("Back","Arial",30);auto norSprite = Scale9Sprite::create("Button/public_ui_blue_btn.png");auto highLightSprite = Scale9Sprite::create("Button/public_ui_green_btn.png");auto outPutBtn = ControlButton::create(btnTitle,norSprite);outPutBtn->setBackgroundSpriteForState(highLightSprite,Control::State::HIGH_LIGHTED);outPutBtn->setPosition(ccp(visibleSize.width-norSprite->getContentSize().width/2,visibleSize.height - norSprite->getContentSize().height));outPutBtn->addTargetWithActionForControlEvents(this,cccontrol_selector(GetBackLayer::getBack),Control::EventType::TOUCH_UP_INSIDE);this->addChild(outPutBtn,20);return true;}void GetBackLayer::getBack(Ref* pSender,Control::EventType event){CCLOG("Back to MainScene");auto scene = MainScene::createScene();Director::getInstance()->replaceScene(scene);}

Here, because extension is used, some problems will occur: the solution has been mentioned before:

Three steps:Graphic explanation

Now, you can try using backbutton, so the getbacklayer can be added to many scene

Now let's take a look at poseditorlayer. h.

Class poseditorlayer: Public layer {public: poseditorlayer ();~ Poseditorlayer (); create_func (poseditorlayer); Virtual bool Init (); Private: // ** 2 ** current level int _ curlevel; // ------------ Member & function cutting line -------------------- // ** 2 ** pre-loaded content void preload ();};
. Cpp

Poseditorlayer: poseditorlayer () {_ curlevel = 1;} poseditorlayer ::~ Poseditorlayer () {} bool poseditorlayer: Init () {// ** 2 *** ----------------- touch event ---------------------------- auto listener = eventlistenertouchonebyone: Create (); listener-> setswallowtouches (true); listener-> ontouchbegan = [] (touch * touch, event * event) {return true ;}; listener-> ontouchmoved = [] (touch * touch, event * event) {}; listener-> ontouchended = [=] (touch * touch, event * event) {auto touchpos = touch-> getlocationinview (); Auto Pos = Director: getinstance ()-> converttoui (touchpos); cclog ("Touch POS. X is % F, touch POS. Y is % F ", POS. x, POS. y) ;}; _ eventdispatcher-> addeventlistenerwithscenegraphpriority (listener, this); // optional // ** 2 ** preload (); Return true;} void poseditorlayer :: preload () {// ** 2 ** add mapauto visiblesize = Director: getinstance ()-> getvisiblesize (); Auto SBG = _ string :: createwithformat ("game/level_0000d.jpg", _ curlevel); Auto mapbg = sprite: Create (SBG-> getcstring (); mapbg-> setposition (CCP (visiblesize. width/2, visiblesize. height/2); mapbg-> setopacity (150); this-> addchild (mapbg );}
Add this layer to poseditorscene. To avoid blocking getbacklayer, you can add it to scene before getbacklayer.

Then let's try F5. The output shows the position of your touch screen.

Touch the screen to add points, so let's take a look at posbase

enum EnumPosType{enTowerPos,enMonsterPos};class PosBase : public Node{public:PosBase();~PosBase();//**2**static PosBase* create(Point pos, EnumPosType posType, bool isDebug);//**2**bool init(cocos2d::Point pos, EnumPosType posType, bool isDebug);//**2**virtual void draw(cocos2d::Renderer *renderer, const kmMat4& transform, bool transformUpdated);protected:CC_SYNTHESIZE(Point,_pos,Pos);//**2**bool _isDebug;EnumPosType _posType;};/**/
Here, a posbase is created based on the location, point type, debugging, and three variables. If yes, the node is drawn based on _ isdebug, the cc_synthesize here is also a macro, that is, adding a private member is equivalent:

PRIVATE:

Point _ Pos;

Public:

Void setpos (point POS) {_ Pos = Pos ;};

Point getpos () {return _ Pos ;};

. Cpp

# Define tower_radius 32 # define monster_radius 10 posbase: posbase () {_ Pos = ccpointmake (0, 0); _ isdebug = false; _ postype = entowerpos;} posbase ::~ Posbase () {} posbase * posbase: Create (point POs, enumpostype postype, bool isdebug) {posbase * TPOs = new posbase (); if (TPOs & TPOs-> Init (Pos, postype, isdebug) {TPOs-> autorelease () ;}else {cc_safe_delete (TPOs);} return TPOs ;} bool posbase: Init (point POs, enumpostype postype, bool isdebug) {// ** 2 ** _ synthesize (point, _ POs, POS ); setpos (POS); _ postype = postype; _ isdebug = isdebug; return true;} void posbase: Draw (Renderer * Renderer, const kmmat4 & transform, bool transformupdated) {If (_ isdebug) {gllinewidth (5); // set the inferred radius float radius Based on posmode; If (_ postype = entowerpos) {radius = tower_radius ;} else {radius = monster_radius;} // draw towerposif (_ postype = entowerpos) {point srcpos = point (_ POS. x-radius, _ POS. Y + radius); point destpos = point (_ POS. X + radius, _ POS. y-radius); ccdrawrect (srcpos, destpos);} else {// draw monsterposccdrawcircle (_ POs, radius, 360, 20, false);} gllinewidth (1 );}}

Then try again: add the member _ postype to the poseditorlayer, and assign the value of entowerpos to the constructor to indicate that the current coordinates are edited by default.

Member function editorpos

void PosEditorLayer::editPos(Point pos){//**2**testauto posBase = PosBase::create(pos, _posType, true);this->addChild(posBase);}

Then, add a function to the touch event to add a point to the screen;


4. Knowledge Point preview next section

Now that you want to edit it, you can only add a vertex or delete it? What is the need to change postype in the code? Can I only edit Level 1 checkpoints? Are these points not saved?

Solution

------------------------------------------------

Resource & code
------------------------------------------------
Personal ignorance. Thank you for your correction and discussion.





Cocos2d-x 3.0 game instance learning notes "tower guard" Step 2 --- Editor (1) -- touch add point

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.