Cocos2D Simple Collision Detection

Cocos2D Simple Collision Detection

Postby BenChang » Fri Sep 11, 2015 7:04 am

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.
User avatar
BenChang
 
Posts: 176
Joined: Mon Jan 17, 2011 4:48 pm

Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest

cron