Guest User

Untitled

a guest
Jun 18th, 2012
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. Pixel-Perfect Collision Detection Android
  2. int left = max(obj1.left, obj2.left)
  3. int right = min(obj1.right, obj2.right)
  4. int top = min(obj1.top, obj2.top)
  5. int bottom = max(obj1.bottom, obj2.bottom)
  6.  
  7. for (int x = left; x < right; x++) {
  8. for (int y = top; y < bottom; y++) {
  9. if (obj1.isFilled(x,y) && obj2.isFilled(x,y)) {
  10. return true;
  11. }
  12. }
  13. }
  14.  
  15. public class CollisionUtil {
  16. public static boolean isCollisionDetected(Sprite sprite1, Sprite sprite2){
  17. Rect bounds1 = sprite1.getBounds();
  18. Rect bounds2 = sprite2.getBounds();
  19.  
  20. if( Rect.intersects(bounds1, bounds2) ){
  21. Rect collisionBounds = getCollisionBounds(bounds1, bounds2);
  22. for (int i = collisionBounds.left; i < collisionBounds.right; i++) {
  23. for (int j = collisionBounds.top; j < collisionBounds.bottom; j++) {
  24. int sprite1Pixel = getBitmapPixel(sprite1, i, j);
  25. int sprite2Pixel = getBitmapPixel(sprite2, i, j);
  26. if( isFilled(sprite1Pixel) && isFilled(sprite2Pixel)) {
  27. return true;
  28. }
  29. }
  30. }
  31. }
  32. return false;
  33. }
  34.  
  35. private static int getBitmapPixel(Sprite sprite, int i, int j) {
  36. return sprite.getBitmap().getPixel(i-(int)sprite.getX(), j-(int)sprite.getY());
  37. }
  38.  
  39. private static Rect getCollisionBounds(Rect rect1, Rect rect2) {
  40. int left = (int) Math.max(rect1.left, rect2.left);
  41. int top = (int) Math.max(rect1.top, rect2.top);
  42. int right = (int) Math.min(rect1.right, rect2.right);
  43. int bottom = (int) Math.min(rect1.bottom, rect2.bottom);
  44. return new Rect(left, top, right, bottom);
  45. }
  46.  
  47. private static boolean isFilled(int pixel) {
  48. return pixel != Color.TRANSPARENT;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment