How to use the Rect.intersect method.
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.
Kohler Fryer
Updated on June 16, 2022Comments
-
Kohler Fryer about 2 years
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);
orcollision = mSquare.intersect(jSquare); if(collision==true){ canvas.drawColor(Color.RED); } this always returns false no matter where the rectangles are.......
-
Kohler Fryer over 12 yearsIve tried a bunch of things but nothing seems to work..... Here is how far i got but these methods dont work... if (Rect.intersects(mSquare, mSquare)){ canvas.drawColor(Color.LTGRAY); } ................. or.......... boolean collision = mSquare.intersect(jSquare); if (collision == true){ canvas.drawColor(Color.LTGRAY); } The canvas never changes! please help im screwed.
-
slayton over 12 years
Rect.intersect
is NOT a static method, meaning it needs to be called on an instance of an object. The correct way to check for an intersetction between two rectangles, lets call themr1
andr2
is to call the method like this:r1. intersect(r2)
NOTRect.intersect(r1,r2)
see the android Rect docs for more information developer.android.com/reference/android/graphics/Rect.html -
Kohler Fryer over 12 yearsAlright that makes sense but ive tried that...Maybe I cant check for an intersection on a canvas...?
-
slayton over 12 yearscan you post an update to your question with what code you've tried and describe why it isn't working?
-
Kohler Fryer over 12 yearsAlright. Thanks so much for the help man it means a lot foreals.
-
Kohler Fryer over 12 yearsboolean collision = mSquare.intersect(jSquare);.................. if(collision==true){ canvas.drawColor(Color.BLACK); }
-
Kohler Fryer over 12 yearsIt should be working but it doesnt give me a true or false return
-
Kohler Fryer over 12 yearsif(mSquare.intersect(jSquare)){ canvas.drawColor(Color.BLACK);} --also doesnt work
-
slayton over 12 yearsTry using Log messages to verify the data in the Rect objects
-
Kohler Fryer over 12 yearsthanks You set me in the right direction ... took me forever but i found out that my stupid rectangle didnt follow this sizing ---left <= right and top <= bottom.