How to use the Rect.intersect method.
Asked Answered
A

1

6

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....... 
Aalesund answered 29/2, 2012 at 0:58 Comment(0)
I
6

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.

Intercessory answered 29/2, 2012 at 2:47 Comment(10)
Ive 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.Aalesund
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 them r1 and r2 is to call the method like this: r1. intersect(r2) NOT Rect.intersect(r1,r2) see the android Rect docs for more information developer.android.com/reference/android/graphics/Rect.htmlIntercessory
Alright that makes sense but ive tried that...Maybe I cant check for an intersection on a canvas...?Aalesund
can you post an update to your question with what code you've tried and describe why it isn't working?Intercessory
Alright. Thanks so much for the help man it means a lot foreals.Aalesund
boolean collision = mSquare.intersect(jSquare);.................. if(collision==true){ canvas.drawColor(Color.BLACK); }Aalesund
It should be working but it doesnt give me a true or false returnAalesund
if(mSquare.intersect(jSquare)){ canvas.drawColor(Color.BLACK);} --also doesnt workAalesund
Try using Log messages to verify the data in the Rect objectsIntercessory
thanks 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.Aalesund

© 2022 - 2024 — McMap. All rights reserved.