David Elliott
David Elliott

Reputation: 113

Android ImageView Collision Detection?

I'm trying to make something happen when two ImageViews intersect each other. This is the code that I used:

Rect rect1 = new Rect();
imageView.getHitRect(rect1);
Rect rect4 = new Rect();
imageView2.getHitRect(rect4);

boolean collision = false; 
collision = rect1.intersect(rect4);
if(collision = true){
    button.setText("collided"); 
}else
    button.setText("not collided"); 

However, the boolean just changed to true when the app starts. The first ImageView stays still while the other moves towards the first one (it's not a sprite, but it moves in the direction of the first ImageView and moves past it). I want the boolean to change when the two ImageViews intersect. Is there something I'm missing?

Upvotes: 2

Views: 4560

Answers (2)

user3137329
user3137329

Reputation:

I searched the Internet for days and this is what worked for me. Amazing.

Remember to check for collisions every second or something

How to know if two images are intersect while one image moving in android?

Upvotes: 0

VVB
VVB

Reputation: 7641

Try this :

 Rect rc1 = new Rect();
 imageView1.getDrawingRect(rc1);
 Rect rc2 = new Rect();
 imageView2.getDrawingRect(rc2);
 if (Rect.intersects(rc1, rc2) {
   // intersection is detected
   // here is your method call
 }

Upvotes: 5

Related Questions