Cocos2d-x "Thunder War" (4)-strategy mode to achieve different bullets switching!!

Source: Internet
Author: User
Tags addchild cos

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

In this paper, we start with the strategy mode in the design mode, and the hero planes switch different bullets in the plane war. There are three kinds of bullets. The first one: each time a bullet, the vertical launch; the second: each two bullets, two are vertical emission: the third one, each with three bullets, both sides of the bullets have a certain angle, and the middle of the bullets fired vertically; Design patterns are often used in game development ideas, suggesting that interested students can be well researched! All right, here we go.

The effect is as follows:

Cocos2d-x Version: 3.4

Engineering Environment: VS30213

first, the Strategy mode (stragegy pattern)1. Introduction

Strategy mode is also called the Strategy mode is one of the behavior patterns, it encapsulates a series of algorithms, for all algorithms to define an abstract algorithm interface, and through the inheritance of the abstract algorithm interface to all the algorithm encapsulation and implementation, the specific algorithm selection to the client decision (policy). The strategy mode is mainly used to smooth the switching of algorithms.

2. Intention

Define a series of algorithms, encapsulate them one by one, and they can replace each other. Allows the algorithm to be independent of the customers who use it.

3. Applicability
    • If there are many classes in a system, the difference between them is only their behavior, then using a policy pattern can dynamically allow an object to choose a behavior in many behaviors.
    • A system needs to dynamically select one of several algorithms. Then these algorithms can be packaged into a specific algorithm class, and these algorithm classes are a subclass of an abstract algorithm class. In other words, these specific algorithm classes have a unified interface, because of the polymorphism principle, the client can choose to use any specific algorithm class, and only hold one data type is an abstract algorithm object.
    • The data used by a system's algorithms cannot be made known to the client. The policy pattern avoids the need for the client to relate to the complexity of the algorithm-only data that is not required to be exposed.
    • If a class defines a variety of behaviors, these behaviors appear as multiple conditional statements in the operation of this class. Move the related conditional branches to their respective strategy classes in place of these conditional statements.
For more detailed strategy patterns look here:24-Day Learning design mode------Strategy Mode

two. Code writing for bullet and bullet management classesFirst look at the class UML diagram for this article:


The idea here is that the bullet is fired as a function, the base class bullet is defined as a virtual function, and then the Herobulletone, Herobullettwo and Herobulletthree in the class bullets are implemented in different emission functions respectively. Then there is a private member variable in Herobulletlayer in the bullet management class BulletStyle * Mbulletstyle. When a different bullet needs to be switched, the new Herobulletone or Herobullettwo or Herobulletthree are assigned to Mbulletstyle.
Let's take a look at the code here!!!

2.1 First bullet base class:BulletStyle.h, it is noted here that virtual void Shootbullet (float dt) {} is a virtual function, which means that the different number of bullets is emitted depending on the subclass.
/*** function creates the base class of bullets * author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka) * Time 2015.3.31*/#pragma once#ifndef __ Bulletstyle_h__#define __bulletstyle_h__#include "Cocos2d.h" Using_ns_cc;class bulletstyle:public cocos2d::Node{ Public:~bulletstyle ();/*** Remove All things */void removeallobject ();/*** remove bullets that are outside the screen's visible range or the bullet after the collision clear * @param pnode the bullets to be removed */void Removebullet (node* pnode);/*** According to the incoming aircraft, bullets follow the launch * @param plane for incoming aircraft, can be a hero plane or enemy aircraft */virtual void Createbullet (node* plane);/* * * Fired bullets, in which the bullets are rendered and the bullet's flight action, default to single bullet * @param dt bullet interval time */virtual void Shootbullet (float dt) {}protected://bullet container  Vector <sprite *> Vecbullet; Batch Render node  spritebatchnode* Bulletbatchnode;//Incoming aircraft  
Implementing File BulletStyle.cpp
/*** function base class for creating bullets * Author Lin Bingwen ([email protected] Blog: http://blog.csdn.net/evankaka) * Time 2015.3.31*/#include "BulletStyle.h" Bulletstyle::~bulletstyle () {//removeallobject ();} /*** Remove All things */void bulletstyle::removeallobject () {Bulletbatchnode->removeallchildren (); VecBullet.clear (); This->removeallchildren ();} /*** Remove bullets, remove bullets from the container, and remove */void bulletstyle::removebullet (node* pnode) {if (NULL = = Pnode) {return;} from Spritebatchnode sprite* bullet = (sprite*) pnode;bulletbatchnode->removechild (bullet, true); Vecbullet.eraseobject (bullet);} /*** according to the incoming aircraft, bullets follow the launch * @param plane for incoming aircraft, can be a hero plane or enemy aircraft */void Bulletstyle::createbullet (node* plane) {This->plane = plane ;//Create Batchnode node Bulletbatchnode = spritebatchnode::create ("Bullet1.png"); This->addchild (bulletBatchNode);// Every 0.2S call once fired bullet function schedule (Schedule_selector (Bulletstyle::shootbullet), 0.2f);//Note that the launch method here is left to the subclass to achieve!!! }
2.2 Fired only one bullet class HeroBulletOne.h, note that direct inheritance
/*** feature launches only one bullet at a time * author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka) * Time 2015.3.31*/#pragma once#ifndef __ Herobulletone_h__#define __herobulletone_h__#include "Cocos2d.h" #include "BulletStyle.h" Using_ns_cc;class Herobulletone:public BulletStyle {public:virtual  
Implementation file:
/*** feature launches only one bullet at a time * author Lin Bingwen ([email protected] Blog: http://blog.csdn.net/evankaka) * Time 2015.3.31*/#include " HeroBulletOne.h "void Herobulletone::shootbullet (float dt) {Size winsize = director::getinstance ()->getwinsize (); Auto Planepos = Plane->getposition ();//Create bullets from the cache auto Spritebullet = sprite::createwithtexture (bulletbatchnode-> GetTexture ());//Add the created bullet to the Batchnode for batch rendering Bulletbatchnode->addchild (Spritebullet);// Add the created bullets to the container vecbullet.pushback (Spritebullet); Point Bulletpos = (Point (Planepos.x,planepos.y + plane->getcontentsize (). HEIGHT/2 +));spritebullet->    SetPosition (Bulletpos); Spritebullet->setscale (0.8f); Float flyvelocity = 500;//running speed, can control itself, the pixels per second float Flylen = winsize.height-planepos.y;float realflyduration = flylen/f lyvelocity;//actual flight time//bullet run distance and time, starting from the aircraft to run to the top of the screen auto Actionmove = Moveto::create (Realflyduration,point (bulletpos.x, Winsize.height));//The function callback after the execution of the bullet, called remove bullet function Auto Actiondone = callfuncn::create (Cc_callback_1 (herobulletone:: Removebullet, this))///bullets start running sequence* sequence = Sequence::create (Actionmove, Actiondone, NULL); spritebullet->runaction (sequence);} 
2.3 Launch two Bullets class HeroBulletTwo.h, note that direct inheritance
/*** features two bullets per launch * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka) * Time 2015.3.31*/#pragma once#ifndef __ Herobullettwo_h__#define __herobullettwo_h__#include "Cocos2d.h" #include "BulletStyle.h" Using_ns_cc;class Herobullettwo:public BulletStyle {public:virtual  
Implementation file:
/*** features two bullets per launch * Author Lin Bingwen ([email protected] Blog: http://blog.csdn.net/evankaka) * Time 2015.3.31*/#include " HeroBulletTwo.h "void Herobullettwo::shootbullet (float dt) {Size winsize = director::getinstance ()->getwinsize (); Auto Planepos = Plane->getposition ();//Create bullets from the cache auto Spritebullet1 = sprite::createwithtexture (bulletbatchnode- >gettexture ()); auto Spritebullet2 = Sprite::createwithtexture (Bulletbatchnode->gettexture ());// Add the created bullets to the Batchnode for batch rendering Bulletbatchnode->addchild (SPRITEBULLET1); Bulletbatchnode->addchild ( SPRITEBULLET2);//Add the created bullet to the container vecbullet.pushback (SPRITEBULLET1); Vecbullet.pushback (Spritebullet2); Point bulletPos1 = (Point (Planepos.x-plane->getcontentsize (). Width/4,planepos.y + plane->getcontentsize (). HEIGHT/2+10)); Point BulletPos2 = (Point (planepos.x + plane->getcontentsize (). Width/4,planepos.y + plane->getcontentsize (). HEIGHT/2+10)); Spritebullet1->setposition (BULLETPOS1); Spritebullet1->setscale (0.8f);spritebullet2-> SetPosition (bULLETPOS2); Spritebullet2->setscale (0.8f); Float flyvelocity = 500;//running speed, can control itself, the pixels per second float Flylen = winsize.height-planepos.y;float realflyduration = flylen/f lyvelocity;//actual flight time//the distance and time of the bullet run from the aircraft to the top of the screen auto actionMove1 = Moveto::create (Realflyduration,point ( bulletpos1.x, winsize.height)); Auto ActionMove2 = Moveto::create (Realflyduration,point (bulletpos2.x, Winsize.height ), or//The function callback after the execution of the bullet, call remove bullet function Auto Actiondone = callfuncn::create (Cc_callback_1 (Herobullettwo::removebullet, this)) ;//bullets start running sequence* Sequence1 = Sequence::create (actionMove1, Actiondone, NULL); Spritebullet1->runaction ( SEQUENCE1); sequence* Sequence2 = sequence::create (ActionMove2, Actiondone, NULL); Spritebullet2->runaction (SEQUENCE2);}
2.4 Launch three Bullets class HeroBulletThree.h, note that direct inheritance
Implementation file:
/*** features three bullets per launch * Author Lin Bingwen ([email protected] Blog: http://blog.csdn.net/evankaka) * Time 2015.3.14*/#include " HeroBulletThree.h "void Herobulletthree::shootbullet (float dt) {Size winsize = director::getinstance ()->getwinsize Auto Planepos = plane->getposition ();d ouble angle = m_pi * 80/180;//rotation angle//Create bullets from cache auto Spritebullet = Sprite::cre Atewithtexture (Bulletbatchnode->gettexture ()); auto Spritebullet1 = Sprite::createwithtexture (bulletbatchnode- >gettexture ()); Spritebullet1->setrotation (-angle); auto Spritebullet2 = Sprite::createwithtexture ( Bulletbatchnode->gettexture ()); spritebullet2->setrotation (angle);// Add the created bullets to the Batchnode for batch rendering Bulletbatchnode->addchild (Spritebullet); Bulletbatchnode->addchild ( SPRITEBULLET1); Bulletbatchnode->addchild (Spritebullet2);//Add the created bullets to the container vecbullet.pushback (Spritebullet); Vecbullet.pushback (SPRITEBULLET1); Vecbullet.pushback (Spritebullet2); Point Bulletpos = (Point (Planepos.x,planepos.y + plane->getcontentsize (). HEIGHT/2 + 20)); PoinT bulletPos1 = (point (Planepos.x-plane->getcontentsize (). Width/4-10,planepos.y + plane->getcontentsize (). HEIGHT/2+10)); Point BulletPos2 = (Point (planepos.x + plane->getcontentsize (). Width/4+10,planepos.y + plane->getcontentsize (). HEIGHT/2+10)); Spritebullet->setposition (Bulletpos); Spritebullet->setscale (0.8f);spritebullet1-> SetPosition (BULLETPOS1); Spritebullet1->setscale (0.8f); spritebullet2->setposition (BULLETPOS2);    Spritebullet2->setscale (0.8f); Float flyvelocity = 500;//run speed, you can control the pixels per second of float Flylen = winsize.height-planepos.y;float flyLen1 = Planepos.x/cos (A Ngle)///by degrees float FlyLen2 = (winsize.width-planepos.x)/cos (angle); float realflyduration = flylen/flyvelocity;//actual flight Time float realFlyDuration1 = flylen1/flyvelocity;//actual flight time float RealFlyDuration2 = flylen2/flyvelocity;//actual flight time// The distance and time of the bullet run from the plane to the top of the screen auto Actionmove = Moveto::create (Realflyduration,point (bulletpos.x, winsize.height)); auto actionMove1 = Moveto::create (reaLflyduration1,point (0, Planepos.x*tan (angle) + planepos.y)); Auto ActionMove2 = Moveto::create (realflyduration2,point (Winsize.width, (winsize.width-planepos.x) *tan (angle) + planepos.y)); /A function callback after execution of the bullet, call remove bullet function Auto Actiondone = callfuncn::create (Cc_callback_1 (Herobulletthree::removebullet, this));// The bullets start running sequence* sequence = Sequence::create (Actionmove, Actiondone, NULL); spritebullet->runaction (sequence); sequence* Sequence1 = sequence::create (actionMove1, Actiondone, NULL); Spritebullet1->runaction (Sequence1); sequence* Sequence2 = sequence::create (ActionMove2, Actiondone, NULL); Spritebullet2->runaction (SEQUENCE2);}

2.5. Write the Bullet Manager
Implementation file:
/*** feature manages bullets, toggles different bullets * Author Lin Bingwen ([email protected] Blog: http://blog.csdn.net/evankaka) * Time 2015.3.31*/#include " HeroBulletLayer.h "Herobulletlayer::herobulletlayer (node* heroplane) {This->heroplane = Heroplane;mbulletstyle = Null;bulletnumber = 1;} /*** static method of creating bullets * @param heroplane for Hero Aircraft */herobulletlayer* Herobulletlayer::create (node* heroplane) {herobulletlayer* PRet = new Herobulletlayer (Heroplane), if (Pret&&pret->init ()) {pret->autorelease (); return pRet;} Else{delete Pret;pret = Null;return NULL;}} BOOL Herobulletlayer::init () {bool BRet = false;do {cc_break_if (! Layer::init ()); Mbulletstyle = new Herobulletone (); Mbulletstyle->autorelease (); Mbulletstyle->createbullet ( Heroplane); This->addchild (mbulletstyle); bRet = true;} while (0); return bRet;} /*** switch between different bullets * @param number indicates the amount of bullets */void herobulletlayer::changebullet (int numbers) {switch (number) {Case 1:if ( Bulletnumber! = 1) {This->removechild (Mbulletstyle, true); Mbulletstyle = new Herobulletone (); bulletnumber = 1; mbulletstyle->createbullet (Heroplane); Mbulletstyle->autorelease (); This->addchild (Mbulletstyle);} Break;case 2:if (Bulletnumber! = 2) {This->removechild (Mbulletstyle, true); Mbulletstyle = new Herobullettwo (); Bulletnumber = 2;mbulletstyle->createbullet (Heroplane); Mbulletstyle->autorelease (); This->addChild ( Mbulletstyle);} Break;case 3:if (Bulletnumber! = 3) {This->removechild (Mbulletstyle, true); Mbulletstyle = new Herobulletthree (); Bulletnumber = 3;mbulletstyle->createbullet (Heroplane); Mbulletstyle->autorelease (); This->addChild ( Mbulletstyle);} Break;default:break;}}

2.6. Call method Game Portal Main file GameMain.h add header file
     #include "HeroBulletLayer.h"//This is the layer of bullet management
Add Variable:
    Herobulletlayer *mherobulletlayer;

Then the GameMain.cpp in the implementation method is added in the init () function

Add bullets    mherobulletlayer = herobulletlayer::create (Mheroplane);    This->addchild (mherobulletlayer,1);
Note that Mheroplane is your hero. Airplane class, is the above can follow the finger movement mobile phone, do not know to see here,cocos2d-x "Thunder War" (2)-The genie moves with his finger, where do you go? This is not yet a singleton pattern, and will be changed later .!
Then it's switching bullets:
All you need to do is switch the bullets:
Fire a bullet.
Mherobulletlayer->changebullet (1);
Launch two bullets.
Mherobulletlayer->changebullet (2);
Launch three bullets.
Mherobulletlayer->changebullet (3);

Here I set the bullet type to automatically switch to each 5 seconds for testing:
GameMain.h Add a variable
int number;//Indicates the type of the current bullet

Added in the init () function in GameMain.cpp:
Every 5S changes the sub-bomb type number    = 1;    Schedule (Schedule_selector (Gamemain::changebullet), 5.0f);


Here is the method of the timer
void Gamemain::changebullet (float dt) {if (number = = 1) {Mherobulletlayer->changebullet (2); number = 2;} else if (number = = 2) {Mherobulletlayer->changebullet (3); number = 3;} else if (number = = 3) {Mherobulletlayer->changebullet (1); number = 1;} Cclog ("Change");}


Effect:
Here it will automatically switch different bullets every 5s, due to the limitations of uploading pictures. It's the only way.



Iii. SummaryIsn't it convenient? When I need to add a bullet type, I only need to inherit bulletstyle. Then rewrite the function shootbullet (float DT). Then in the position where the bullet needs to be changed, bool Herobulletlayer::changebullet (int number) increases every 4 bullets. The 5th Seed bomb ... This increases the reusability of the code and is easy to understand. It also saves a whole bunch of if-else judgments.

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Cocos2d-x "Thunder War" (4)-strategy mode to achieve different bullets switching!!

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.