Posted By

shalomfriss on 06/05/11


Tagged

Objective-c iphone


Versions (?)

Pixel perfect collision detection


 / Published in: iPhone
 

  1. //1) Load the image:
  2. UIImage *collisionImage = [UIImage imageNamed:@"levelmask.png"];
  3.  
  4. //2) Get the image size:
  5. int width = (int)collisionImage.size.width;
  6. int height = (int)collisionImage.size.height;
  7.  
  8. //3) Allocate our array for quick lookups and clear it:
  9. unsigned char *collisionMap = (unsigned char *)malloc( width *
  10. height );
  11. memset( collisionMap, 0, width * height );
  12.  
  13. //4) Get access to the raw bits of the image
  14. CFDataRef imageData = CGDataProviderCopyData( CGImageGetDataProvider
  15. ( collisionImage.CGImage ) );
  16. const UInt32 *pixels = (const UInt32*)CFDataGetBytePtr( imageData );
  17.  
  18. //5) Build our collision map:
  19. for( j = 0; j < (width * height); j++ )
  20. if ( pixels[j] & 0xff000000 ) collisionMap[j] |= 1;
  21.  
  22. //6) Release what we no longer need:
  23. CFRelease( imageData );
  24.  
  25. //Now, whenever you need to see if you hit something, you call a routine
  26. //that does:
  27. -(int)collisionForPoint:(CGPoint)point
  28. {
  29. int x = (int)point.x;
  30. int y = (int)point.y;
  31.  
  32. // TODO: check for boundaries here
  33.  
  34. return collisionMap[(y*width)+x];
  35.  
  36. }

Report this snippet  

You need to login to post a comment.