Page 1 of 1

Cocos2D Simple Collision Detection

PostPosted: Fri Sep 11, 2015 7:04 am
by BenChang
The simplest way to do collision detection is with either a radius comparison or a bounding box comparison. Here's how to do a bounding box collision test. We'll do this in the update() function, so we can check for collisions every frame.

First, in the main GameLayer class, enable the use of the update function in ctor:

Code: Select all
this.scheduleUpdate();


now Cocos will look for an update() function attached to this node at every frame.

Here's the update function

Code: Select all
update:function (dt) {
       this.CheckCollisions();
    },
   
    CheckCollisions:function() {
       if (cc.rectIntersectsRect (this.squid.getBoundingBox(), this.urchin.getBoundingBox()))
       {
          this.squid.setColor (new cc.Color(255,0,0));
       }
       else
       {
          this.squid.setColor (new cc.Color(255,255,255));
       }
    },


with more urchins, you'd store them in an array and compare the squid's bounding box with each of them.

The accuracy can be refined, though if you want very accurate collision detection, you may want to look at the Chipmunk Physics library examples for Cocos.