How to use the Rect.intersect method.

Ive created a game in which you move a rectangle and dodge other falling rectangles from the sky. Although every time 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....... 
+4
source share
1 answer

There are many ways to do this, the simplest would be to get a bounding Rect for each Bitmap and each time to check for a conflict using the Rect.intersect() method.

Something like that:

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

In addition, there are many other (better) ways to do this, especially when working with objects that are not rectangles, and when there are many objects on the screen. Check this post for a good discussion.

There's also an excellent chapter on collision detection in the Beginning of Android Games book, and the book is well worth reading if you plan to write a game.

+4
source

Source: https://habr.com/ru/post/1398933/


All Articles