socrates
socrates

Reputation: 124

Collision Detection in cocos2d-x

I am beginner in cocos2d-x and I am developing a game using cocos2d-x in xcode. In my game I added a player sprite named man and an obstacle sprite named obs1. Now I am trying to collide each other. For that I am using the following code but in the run time while enter into the Playscene it is showing some error in getpositionX and getpositionY. I declared the kman and kobs1 as enum in my header file. Please help me to solve this.

   schedule(schedule_selector(PlayScene::update));


 void PlayScene::update(float dt)
{
CCSprite *man = (CCSprite*)getChildByTag(kman);
CCSprite *obs1 = (CCSprite*)getChildByTag(kobs1);
CCRect manRect   = CCRectMake(man->getPositionX(),man->getPositionY(),6,1);
CCRect obs1Rect     = CCRectMake(obs1->getPositionX(),obs1->getPositionY(),6,1);

if(manRect.intersectsRect(obs1Rect))
{
    CCDirector::sharedDirector()->end();

}

}

Thanks.

Upvotes: 0

Views: 1966

Answers (2)

ApDheeraj
ApDheeraj

Reputation: 101

You Can Use

man->getBoundingBox() (Return a Rect)
obs1->getBoundingBox() (Return another Rectangle

and check

if(man-> intersectsRect(obs1)
{

// Do Something 
}

Thanks

Upvotes: 3

Andrea Sindico
Andrea Sindico

Reputation: 7440

Why don't you exploit one of the two physics engine provided in COCOS2D (Chipmunk or Box2D)

http://chipmunk-physics.net/release/ChipmunkLatest-Docs/

http://www.iforce2d.net/b2dtut/collision-callbacks

In both the cases you have to define the rules of your world (i.e. gravity vector, borders, etc.) and objects for each elements of your game that you want follow the rules of physics (i.e. mass, dimensions, etc.). Then you can bind these objects to your sprites so that the sprite position and angle is updated according to the physical object. Also you can bind callback for which are invoked when two objects collide.

Upvotes: 0

Related Questions