Cocos2d-x Collision Detection principle and heroes to kill monsters--game development "Zhao Yun to Fight" (7)

Source: Internet
Author: User
Tags addchild

Here is Evankaka's blog, Welcome to discuss and communicate with you before ~~~~~~

Reprint Please specify the source http://blog.csdn.net/evankaka/article/details/42689689

This article will describe in detail the collision detection principle of heroes and monsters in Cocos2dx, which is actually the clash detection of elves and Elves ha. In this paper, we mainly start with the collision of rectangle, write a function of collision detection, and apply it in the game. On the other hand, when the hero strikes, if the hero and the monster collide, the monster will drop the blood, and when the monster's blood is 0 o'clock, the monster died, before death it will fall on the ground flashing a few. Now, let's go.

Cocos2d-x version: 2.2.5

Engineering Environment: WINDOWS7+VS2010

Open by: Put the project under the project folder in the Cocos2d-x installation directory with VS Open

SOURCE Download (Bo Master decided this series of resources all free ~)

First look at the effect:



Directory

First, the Spirit Collision detection principle

Second, custom collision detection function

Three, heroes to kill monsters

Iv. Summary of Ideas


First, the Spirit Collision detection principle

Collision Detection Online There are many people speaking, but generally only talk about how to use, also did not specifically talk about the principle, oneself down on the next, found that actually this is really simple.

First, let's take a look at two rectangles, we define two rectangles, 1: Red, Rectangle 2: Black


If we list all of their non-collision situations, then the other is not collision, think of this, I start from this, and then they do not collide with the situation we can be divided into four kinds

Rectangle 1: Red; Rectangle 2: Black

1. Rectangle 1 to the left of the rectangle 2, the two do not collide



Conditions of Incorporation: x1+w1*0.5<x2-w2*0.5

2. Rectangle 1 to the right of the rectangle 2, the two do not collide


Conditions of Incorporation:: x1-w1*0.5>x2+w2*0.5


3. Rectangle 1 below the rectangle 2, no collision


Conditions of Incorporation:: y1+h1*0.5<y2-h2*0.5

4. Rectangle 1 above the rectangle 2, no collision


Conditions of Incorporation: y1-h1*0.5>y2+h2*0.5

The above four kinds is all the non-collision situation, and then we make a judgment, in turn, detect the above four situations, once found that there is a situation, return no collision, if four cases are not established, then congratulations, the collision succeeded!

Second, custom collision detection function

Collision detection can be used for Elf classes

Sprite1->boundingbox (). Intersectsrect (sprite1->boundingbox ())

But I this game of heroes and monsters are their own definition of the class, so directly call the above function is a bit of a problem, so I put the previous collision detection principle write a function, you can call directly, do not care what you are to the image.

First, where collision detection is used, include "HelloWorldScene.h"

Defining functions

Rectangular Collision Detection
BOOL Isrectcollision (Ccrect rect1, Ccrect rect2);


Then in its implementation function HelloWorldScene.cpp:

Collision detection BOOL Helloworld::isrectcollision (ccrect rect1, Ccrect rect2) {float X1 = rect1.origin.x;//Rectangle 1 center Point of the horizontal axis float y1 = Rec t1.origin.y;//Rectangle 1 Center Point of the ordinate float w1 = rect1.size.width;//Rectangle 1 Width Float h1 = rect1.size.height;//rectangle 1 height Float x2 = Rect2.origin.x;float y2 = rect2.origin.y;float W2 = rect2.size.width;float H2 = rect2.size.height;if (x1+w1*0.5<x2-w2 *0.5)  return false;//Rectangle 1 to the left of the rectangle 2, both collision-free else if (x1-w1*0.5>x2+w2*0.5) return false;//Rectangle 1 to the right of the rectangle 2, both collision-free else if (y1+h1 *0.5<y2-h2*0.5) return false;//rectangle 1 below the rectangle 2, both without colliding else if (y1-h1*0.5>y2+h2*0.5) return false;//rectangle 1 above the rectangle 2, The two do not collide return true;}
The principle of this code is what we said above, very simple!

Three, heroes to kill monsters

Now we're going to call the two functions, let's take a look at the collision range of heroes and monsters.


(I've made the background transparent, that's what it really is)

(I've made the background transparent, that's what it really is)

So, be careful here. Here is to be careful, it is best not to the whole picture width and height are included;

A simple process for collision detection




And then it's realized.

The Void Helloworld::update (float delta) function is added

if (hero->isattack)//hero is attacking {  if (!monster1->isdead)//Monsters are not dead  {    if (ABS (Hero->getpositiony)- Monster1->getpositiony ()) <30)//Monsters and heroes should be in a similar level of height, the attack    is effective {            //detect collisions to monsters, here to be careful to subtract some of the border value      if ( This->isrectcollision (Ccrectmake (Hero->getpositionx (), Hero->getpositiony (), Hero->GetSprite () Getcontentsize (). width-70, Hero->getsprite ()->getcontentsize (). height-30), Ccrectmake (monster1-> Getpositionx (), Monster1->getpositiony (), Monster1->getsprite ()->getcontentsize (). width-30,monster1- >getsprite ()->getcontentsize (). height-20))          {        monster1->hurtanimation ("Monster_hurt", 2, Monster1->monsterdirecton);//Injured}}}  }


Okay, here's a story about the monster injury, the death animation.

And then the previous Monster.h add function

Injured animation void hurtanimation (const char *name_each,const unsigned int num,bool run_directon);//Injury animation end void Hurtend ();// Determine if the injury animation bool ishurt;//death animation void deadanimation (const char *name_each,const unsigned int num,bool run_directon);// Death animation ends void Deadend ();//Judging whether death bool isdead;//monster death flashes end void Blinkend ();
then in the implementation function Monster.cpp

Injured animation void monster::hurtanimation (const char *name_each,const unsigned int num,bool run_directon) {if (ishurt| | Isdead) return;//Injury priority if (Isrunning| | Isattack) {m_monstersprite->stopallactions ();//The current sprite stops all animation//restore sprites from the original initialization map This->removechild (M_monstersprite, TRUE);//Remove the original sprite m_monstersprite=ccsprite::create (monster_name);//Restore the original texture of the wizard m_monstersprite->setflipx (  Monsterdirecton);  This->addchild (M_monstersprite);  Isrunning=false; Isattack=false;}  ccanimation* animation = Ccanimation::create ();  for (int i=1;i<=num;i++) {char szname[100] = {0};  sprintf (SzName, "%s%d.png", name_each,i); Animation->addspriteframewithfilename (SzName);  Load the animated frame} animation->setdelayperunit (2.8f/14.0f);  Animation->setrestoreoriginalframe (TRUE); Animation->setloops (1); Animation Loop 1 times//wrap the animation into an action ccanimate* act=ccanimate::create (animation);//Create callback action, end of injury animation call Hurtend () cccallfunc* callfunc= Cccallfunc::create (This,callfunc_selector (monster::hurtend));//Create a continuous action ccactioninterval* Hurtackact=ccsEquence::create (Act,callfunc,null); m_monstersprite->runaction (hurtackact); Ishurt=true;} Injured animation end void Monster::hurtend () {ishurt=false; Monster_xue->setcurrentprogress (Monster_xue->getcurrentprogress () -10); if (monster_xue-> Getcurrentprogress () ==0) {//play Monster Death animation deadanimation ("Monster_dead", 2,monsterdirecton);}} Death animation void Monster::D eadanimation (const char *name_each,const unsigned int num,bool run_directon) {isdead=true;  ccanimation* animation = Ccanimation::create ();  for (int i=1;i<=num;i++) {char szname[100] = {0};  sprintf (SzName, "%s%d.png", name_each,i); Animation->addspriteframewithfilename (SzName);  Load the animated frame} animation->setdelayperunit (2.8f/14.0f);  Animation->setrestoreoriginalframe (TRUE); Animation->setloops (1); Animation Loop 1 times//wrap the animation into an action ccanimate* act=ccanimate::create (animation);//Create callback action, call Deadact () cccallfunc* callfunc= after the end of death Cccallfunc::create (This,callfunc_selector (Monster::D eadend))//Create continuous action ccactioninterval* deadact=ccsequence:: Create (act,callfunc,null); m_monstersprite->runaction (deadact); }//death animation ends void Monster::D eadend () {//Restores the appearance of Death This->removechild (m_monstersprite,true);//Remove the original sprite M_monstersprite =ccsprite::create ("Monster_dead2.png");//restore the appearance of Death M_monstersprite->setflipx (Monsterdirecton);this-> AddChild (m_monstersprite);//There is a blood bar if (monster_xue!=null) {if (Monsterdirecton)//Because the Monster Center is not in the center of the picture, so only according to the face of the monster, Set the horizontal axis of the Blood Bar Monster_xue->setposition (CCP (M_monstersprite->getpositionx () +60, M_monstersprite->getpositiony ()));//Set on Monsters above Elsemonster_xue->setposition (CCP (M_monstersprite->getpositionx () -60, m_monstersprite-> Getpositiony ())); }//monster flashes twice and then dies ccblink* blinkact=ccblink::create (3,6);//3 is duration, 6 is the number of flashes//Create callback action, call blinkend after flashing end () cccallfunc* callfunc= Cccallfunc::create (This,callfunc_selector (monster::blinkend));//Create a continuous action ccactioninterval* deadact=ccsequence:: Create (Blinkact,callfunc,null); m_monstersprite->runaction (deadact);} Flashing end void Monster::blinkend () {This->removeallchildren ();//Remove monsters and blood strips;}

Monster death of a process, in each injury after the blood, immediately detect the current amount of blood, if the blood volume is 0, immediately play death animation, and then play the flashing animation, and then you can remove the monster off ~ ~ it is so simple

Effect:

1, the Monster in Patrol, when the attack did not detect a collision


2, Heroes in attack, detected a collision, the monster injured and lost blood



3, Monster Blood volume of 0, Monster death, and play flashing animation


Iv. Summary of Ideas

Collision Detection Here I am the other way, and all the possible non-collision is listed, the other is not the collision? And then to do their own programming, on the other hand, the monster is injured, the animation of death, as well as flashing, these are very basic, basically the same function, just once you will. It's here to remember that this is a sequential action, just remember that.




Cocos2d-x Collision Detection principle and heroes to kill monsters--game development "Zhao Yun to Fight" (7)

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.