Search code examples
androidcollision-detectionrect

Android collision detection


Description:

I've got a project which is nearly finished now, but I've noticed the collision is not really working. It's a snake-like game that can be controlled via the touch-screen, so sharp (?, sorry german) angles are possible. At the moment I just leave a bit of tolerance (ignore the first 2 sprites) to enable a bit of turning. The main problem is that the sprites are being rotated which results in overdimensional collision boxes. I'm not using any game engines or OpenGL.

Collision Code: offsetX & offsetY are the bitmaps width or height / 2, is called on the head of the snake. Each link in the snake (Bird) is a placeable

public boolean doesHit(Placeable p) {
    int xLen = Math.abs(this.x - p.x);
    int yLen = Math.abs(this.y - p.y);
    if (bmp != null) {
        if (xLen < offsetX + p.offsetX && yLen < offsetY + p.offsetY)
            return true;
    } else {
        if (xLen < Bird.BIG_W[Bird.mUseBird] / 2
                && yLen < Bird.BIG_H[Bird.mUseBird] / 2)
            return true;
    }
    return false;
}

TL;DR / Question:

Is there a way to rotate Rects and then compare them (preferred, as the game is already finished apart from this)? Or would the simplest way be to port to OpenGL / a game engine?


Solution

  • The best option would be to go OpenGL and use rotated polygons with intersects.

    However for quick hack i would change the doesHit() routine to consider the sprites as circles instead of rectangles. This way they will not grow outside bounds when rotated. The price is that collision detecting will be lousy in the corners.