Outdated Docs > Step by Step Cocos2dxSimpleGame Series > Chapter 5 - How to Detect the Collisions

Chapter 5 - How to Detect the Collisions

Our hero can fire bullets now, but the bullets are only visual. So how can they kill their enemies?

In this chapter, we will introduce Collision Detection to implement it.

Firstly, it’s necessary to track the enemies and the bullets.

In the game, we add a tag for these two kinds of sprites to identify them. Let tag = 1 if the sprite is an enemy, and tag = 2 mean it is a bullet. Because CCSprite inherits from CCNode, there is already a member variable m_nTag with methods setTag() and getTag(); we can implement this to identify the different types of sprites.

Add the two member variables below to HelloWorld in HelloWorldScene.h. These are used to store the existing enemies and bullets.

// cpp with cocos2d-x
protected:
    cocos2d::CCArray *_targets;
    cocos2d::CCArray *_projectiles; 

In cocos2d-x, CCMutableArray is an implementation of NSMutableArray in iOS which contains NSObject’s and their subclasses. Something different is that you should specify the concrete category of its members.

Then initialize the two variables in the construct function, new them in init(), and release them in the destruct function.

// cpp with cocos2d-x

// in init()
// Initialize arrays
_targets = new CCArray;
_projectiles = new CCArray;

HelloWorld::~HelloWorld()
{
  if (_targets)
  {
    _targets->release();
    _targets = NULL;
  }

  if (_projectiles)
  {
    _projectiles->release();
    _projectiles = NULL;
  }

  // cpp don't need to call super dealloc
  // virtual destructor will do this
}

HelloWorld::HelloWorld()
:_targets(NULL)
,_projectiles(NULL)
{
}   

Now modify addTarget() to add a new target to targets array, and set its tag to be 1.

// cpp with cocos2d-x
// Add to targets array
target->setTag(1);
_targets->addObject(target);    

Modify ccTouchesEnded() to add a new bullet to bullets array, and set its tag to be 2.

// cpp with cocos2d-x
// Add to projectiles array
projectile->setTag(2);
_projectiles->addObject(projectile);    

Then, modify spriteMoveFinished() as follows. Here we remove the sprites from their corresponding arrays.

// cpp with cocos2d-x
void HelloWorld::spriteMoveFinished(CCNode* sender)
{
  CCSprite *sprite = (CCSprite *)sender;
  this->removeChild(sprite, true);

  if (sprite->getTag() == 1)  // target
  {
    _targets->removeObject(sprite);
  }
  else if (sprite->getTag() == 2) // projectile
  {
    _projectiles->removeObject(sprite);
  }
}   

The function update() below is used to detect collisions every frame, remove the collided bullet and enemy from the scene.
Declare it in HelloWorldScene.h and Define it in HelloWorldScene.cpp.

// cpp with cocos2d-x
void HelloWorld::update(float dt)
{
    CCArray *projectilesToDelete = new CCArray;
    CCArray* targetsToDelete =new CCArray;
    CCObject* it = NULL;
    CCObject* jt = NULL;

    CCARRAY_FOREACH(_bullet, it)
    {
        CCSprite *projectile = dynamic_cast(it);
        CCRect projectileRect = CCRectMake(
                                           projectile->getPosition().x - (projectile->getContentSize().width/2),
                                           projectile->getPosition().y - (projectile->getContentSize().height/2),
                                           projectile->getContentSize().width,
                                           projectile->getContentSize().height);


        CCARRAY_FOREACH(_target, jt)
        {
            CCSprite *target = dynamic_cast(jt);
            CCRect targetRect = CCRectMake(
                                           target->getPosition().x - (target->getContentSize().width/2),
                                           target->getPosition().y - (target->getContentSize().height/2),
                                           target->getContentSize().width,
                                           target->getContentSize().height);

            if (projectileRect.intersectsRect(targetRect))
            {
                targetsToDelete->addObject(target);
                projectilesToDelete->addObject(projectile);
            }
        }
    }

    CCARRAY_FOREACH(targetsToDelete, jt)
    {
        CCSprite *target = dynamic_cast(jt);
        _target->removeObject(target);
        this->removeChild(target, true);
    }

    CCARRAY_FOREACH(projectilesToDelete, it)
    {
        CCSprite* projectile = dynamic_cast(it);
        _bullet->removeObject(projectile);
        this->removeChild(projectile, true);
    }


    projectilesToDelete->release();
    targetsToDelete->release();
}   

Ok, the last thing we should do is adding update() to the schedule to let it be called every frame.

// cpp with cocos2d-x
this->schedule( schedule_selector(HelloWorld::update) );    

Compile and run the project, fire the bullets as you like, then: AH..AH.., the enemies are killed one by one.

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.