Hey all, just registered here
Anyway, I’ve got a project I’m working on that’s a Sonic The Hedgehog-esqe game. I’ve done pretty good so far, but I’ve got a question about pixel based collision. Right now I take the two images of the ‘sprites’ that are being checked. Then it goes through and checks if they have a pixel overlapping. Here is a code-snippit:
...
public boolean collidesWith(CollisionMask b)
{
if(b == this)
return false;
Rectangle me = new Rectangle(getX(), getY(), getWidth(), getHeight());
Rectangle you = new Rectangle(b.getX(), b.getY(), b.getWidth(), b.getHeight());
if ( me.intersects(you) )
{
//PixelGrabbler pg = new PixelGrabbler(this, b);
return collided(this, b);
//return pg.collided();
}
//System.out.println("No Collision!");
return false;
}
private boolean collided(CollisionMask a, CollisionMask b)
{
Rectangle ar = new Rectangle(a.getX(), a.getY(), a.getWidth(), a.getHeight());
Rectangle br = new Rectangle(b.getX(), b.getY(), b.getWidth(), b.getHeight());
Rectangle un = ar.union(br);
BufferedImage img1 = new BufferedImage((int)(un.getX() + un.getWidth()), (int)(un.getY() + un.getHeight()), BufferedImage.TYPE_INT_ARGB);
BufferedImage img2 = new BufferedImage((int)(un.getX() + un.getWidth()), (int)(un.getY() + un.getHeight()), BufferedImage.TYPE_INT_ARGB);
Graphics ig = img1.getGraphics();
Graphics ig2 = img2.getGraphics();
ig.setColor(new Color(255, 255, 255, 255));
ig.fillRect(0, 0, (int)(un.getX() + un.getWidth()), (int)(un.getY() + un.getHeight()));
ig.drawImage(a.getImage(), (int)(a.getX()), (int)(a.getY()), null);
ig2.setColor(new Color(255, 255, 255, 255));
ig2.fillRect(0, 0, (int)(un.getX() + un.getWidth()), (int)(un.getY() + un.getHeight()));
ig2.drawImage(b.getImage(), (int)(b.getX()), (int)(b.getY()), null);
return colorOverlap(img1, img2);
}
private boolean colorOverlap(BufferedImage i1, BufferedImage i2)
{
for(int x = 0; x < i1.getWidth(); x++)
{
for(int y = 0; y < i1.getHeight(); y++)
{
if(monochrome(i1.getRGB(x, y)) != 0xFFFFFFFF && monochrome(i2.getRGB(x, y)) != 0xFFFFFFFF)
{
return true;
}
}
}
return false;
}
private int nullAlpha(int rgba)
{
return 0xFF000000 + (rgba & 0x00FFFFFF);
}
private int monochrome(int rgba)
{
if(nullAlpha(rgba) != 0xFFFFFFFF)
return 0xFF000000;
else
return 0xFFFFFFFF;
}
...
My problem occurs when I have more than a few sprites on-screen. This only occurs when I have this code activated so I was wondering if there is any way to optomize it.
Any help would be greatly appreciated!