Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

Coordinate system in Cocos2D

I'm having problems detecting collisions in Cocos2D, because the coordinates I use to see if an object collided are always wrong.

I have the following objects:

  1. All the sprites from a tiled map's layer, containing all the obstacles;
  2. A sprite which is child of another sprite, which is child of the hello world layer (the main layer I'm using, which returns the scene). This sprites continuously moves in the map, and it may collide with the obstacles.

To detect collision I just see look at the distance between 2 sprite's bounding boxes:

inline BOOL collision(CGRect r1, CGRect r2)
{
    CGPoint c1= RectCenter(r1);
    CGPoint c2= RectCenter(r2);
    BOOL result= (fabs(c1.x-c2.x)<MAX(r1.size.width/2.0,r2.size.width/2.0)) && (fabs(c1.y-c2.y)<MAX(r1.size.height/2.0,r2.size.height/2.0));
    return result;
}

I use the boundingBox property to get the coordinate and the size of every sprite. But the coordinates are wrong, and it doesn't detect collisions correctly.

I'm pretty sure that I'm doing something wrong, could someone tell me how is the way to manage all sprites to have the same coordinate system? I also tried with convertToWordSpace, but with no luck.

Upvotes: 0

Views: 103

Answers (1)

Patrick Goley
Patrick Goley

Reputation: 5417

You can do away with collision method in favor of the builtin function for seeing if two CGRects intersect:

CGRectIntersectsRect(r1, r2);

Upvotes: 2

Related Questions