How to check if one rectangle is in another rectangle?

Ok, so I am working on a game, and I found that my opponents do not like my collision detection, which works great for my player. After a little debugging, I found out about this because my enemies are bigger than my tiles, while my player is smaller than my tiles.

Now I need to be able to make big enemies and bosses, so this just will not happen. so I need to figure out the best way to check for collision detection. Here's how I do it now:

up and down:

if((enemy.left > tile.left && enemy.left < tile.right || enemy.right > tile.left && enemy.right < tile.right) && enemy.top < tile.bottom && enemy.bottom > tile.top){
    //collision
}

left and right:

if((enemy.top > tile.top && enemy.top < tile.bottom || enemy.bottom > tile.top && enemy.bottom < tile.bottom) && enemy.left < tile.right && enemy.right > tile.left){
     //colision
}
+3
source share
7 answers
+5

, ( , ).

if (firstObject.Left < secondObject.Right && firstObject.Right > secondObject.Left
    && firstObject.Top < secondObject.Bottom && firstObject.Bottom > secondObject.Top)
{
    // Intersecting
}

3, . , . , , , :

http://www.metanetsoftware.com/technique/tutorialA.html#section1

, . , :)

+3

.NET Rectangle.IntersectsWith(Rectangle other) .

+2

, Objective-C, , :

bool CGRectIntersectsRect(CGRect rect1, CGRect rect2)
+2

,

enemy.top < tile.bottom && enemy.bottom > tile.top

( ) , ( )

enemy.top > tile.top && enemy.top < tile.bottom || enemy.bottom > tile.top && enemy.bottom < tile.bottom

+ .

, , , , , :

if((enemy.left > tile.left && enemy.left < tile.right || enemy.right > tile.left && enemy.right < tile.right) && (enemy.top > tile.top && enemy.top < tile.bottom || enemy.bottom > tile.top && enemy.bottom < tile.bottom)){
//collision

}

, / /, true,

+1

, " " . , , :

(enemy.left > tile.left && enemy.left < tile.right
|| enemy.right > tile.left && enemy.right < tile.right)

// graphed as<br>
// TL EL TR ----- or ----- TL ER TR<br>

, :

//  EL TL ----- and ----- TR ER

, , , , . /:

 is_hit :
 // T{L,R,T,B} => tile, E{L,R,T,B} => enemy
 // left-right:
 [
  TL EL TR ----- or ----- TL ER TR
           . or .
  EL TL ----- and ----- TR ER
 ]
 .and.
 // top-bottom:
 [
  TT ET TB ----- or ----- TT EB TB
           . or .
  ET TT ----- and ----- TB EB
 ]
0

A .Netmethod already exists with a name Intersect(Rect rect)in the class Rect.

0
source

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


All Articles