Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the Rect.intersect method.

Ive created a game where you move a rectangle and dodge other falling rectangles from the sky. Though everytime the rectangles intersect nothing happens.

if(mSquare.intersect(jSquare)){ canvas.drawColor(Color.BLACK);
or

collision = mSquare.intersect(jSquare);
     if(collision==true){  canvas.drawColor(Color.RED);
  }  this always returns false no matter where the rectangles are....... 
like image 210
Kohler Fryer Avatar asked Feb 29 '12 00:02

Kohler Fryer


1 Answers

There are a lot of ways to do this, the simplest would be to get the bounding Rect for each Bitmap and on each time step to check for a collision using Rect.intersect() method.

Something like this:

boolean collision = player.getRect().intersect(fallingObject.getRect());

Additionally there are many other (better) ways to do this, especially when dealing with objects that aren't rectangles and when you have lots of objects on the screen. Check out this post for a good discussion

Also the book "Beginning Android Games" has a great chapter about collision detection and the book is well worth a read if you are considering writing a game.

like image 108
slayton Avatar answered Oct 22 '22 05:10

slayton