Rami
Rami

Reputation: 3

Collision detection between two Rect in android

i have draw two rectangles over a canvas using canvas.drawRect(top,left,right,bottom) note that one of the rectangles is static and the other is moving using the android accelerometer.

  1. now i want to detect the collision between those two rectangles

i tried lots of ways but they are not perfect the two rectangles overlaps sometimes so what is the perfect way to detect the collision between them.

that's what i tried hero is the moving triangle maze Component is the static rectangle

            if ((hero.top >= mazeComponent.top)
                && (hero.top <= mazeComponent.bottom)
                && (hero.left <= mazeComponent.right)) {
            collision = true;
        }
        if ((hero.bottom >= mazeComponent.top)
                && (hero.bottom <= mazeComponent.bottom)
                && (hero.right >= mazeComponent.left)) {
            collision = true;
        }
        if ((hero.left >= mazeComponent.left)
                && (hero.left <= mazeComponent.right)
                && (hero.top <= mazeComponent.bottom)) {
            collision = true;
        }
        if ((hero.top >= mazeComponent.top)
                && (hero.top <= mazeComponent.bottom)
                && (hero.left >= mazeComponent.left)) {
            collision = true;
        }
        if ((hero.left >= mazeComponent.left)
                && (hero.left <= mazeComponent.right)
                && (hero.top >= mazeComponent.top)) {
            collision = true;
        }

Upvotes: 0

Views: 1363

Answers (1)

ali2992
ali2992

Reputation: 121

Java/Android Rect and Rectangle objects have an intersect method that could be used to test for a collision

Upvotes: 1

Related Questions