3
votes

in my app I have a player and many enemies (about 100+)..I don't want to use CGRects because it doesn't fits to the enemies. Is there any example how to do pixel perfect collision detection in cocos2d with many sprites?

Some explaination would be great ;)

Thank you very much!

EDIT: I'm using CCSprite and .png files. the png has transparency but it should only detect a collision on non-transparency pixels.

Edit: My enemies are round.

1
hmm.. how big are the enemies??xuanweng
25x25 pixels. Later they will be a little bit smallercocos2dbeginner
would the big image cause a slow down on the detection? Mayby there's another solution for this? (no I don't want to use box2d or chipmunk..it's too big for my purposes)cocos2dbeginner
haha.. y not using cgrects? Pixel collision is even more processor intensive.. Are the shapes closer to round shapes?xuanweng
my shapes are round shapes :D is there a better possibility with round shapes?cocos2dbeginner

1 Answers

4
votes

Circle-circle collision is the easiest.. And computing is the fastest.. I hope you know the radius of the player and radius of enemy.. Let 20 be radius of player and 10 be radius of enemy.. A simple calculation would be:

float dx = player.spr.x - enemy.spr.x;
float dy = player.spr.y - enemy.spr.y;
float dxy = dx*dx + dy*dy;
float collisionRad = (20+10)*(20+10);

if(dxy<= collisionRad)
{
//collision
}

We are calculating distance between 2 points using the Pythagorean Theorem.. http://en.wikipedia.org/wiki/Pythagorean_theorem