delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/10/02/03:45:11

From: G DOT DegliEsposti AT ads DOT it
To: djgpp AT delorie DOT com
Message-ID: <C1256524.002EA05E.00@vega.ads.it>
Date: Thu, 2 Oct 1997 10:45:26 +0200
Subject: Re: Re: collision detection
Mime-Version: 1.0





Hello everybody.

Andrew Deren wrote:
>
> Does anyone know how to detect if two rectangles overlap each other at
> some point. Let's say we have something like this:
>
> typedef struct RECT {
>    int x1, y1, x2, y2;
> } RECT;
>
In many years I have seen it is not possible to solve this problem without
lots
of tests, unless you have some special conditions (and usually you have not
:-)

You have to test for all vertices of A beeing inside B *and* all vertices
of B
beeing inside A, otherwise you can have particular cases where it does not
work.

I alway use another way, which costs almost the same but is simplier to
write:
 if A and B overlap each other then they have an intersection, so I test if
they intersect and the intersection is a real rectangle:

This tests if the intersection of A and B is a valid rectangle (ie x1<x2
and y1<y2)

// A and B must be valid rectangles...
bool overlap(RECT A, RECT B)
{
     // I = intersect(A,B); return isvalid(I);
     return (min(A.x2,B.x1) < max(A.x1,B.x2)) && (min(A.x2,B.x1) <
max(A.x1,B.x2))
}

ciao
  Giacomo




- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019