Path: chuka.playstation.co.uk!news From: Alex Herbert Newsgroups: scee.yaroze.programming.2d_graphics Subject: Re: 2d Collision detection Date: Tue, 13 Oct 1998 15:42:22 +0000 Organization: PlayStation Net Yaroze (SCEE) Lines: 49 Message-ID: <362366CE.AEEA0DC4@ndirect.co.uk> References: <6vggm5$6uj2@scea> <361E1F8A.DA65D1D6@ndirect.co.uk> <6vla90$7882@scea> Reply-To: aherbert@ndirect.co.uk NNTP-Posting-Host: th-usr02-56.ndirect.co.uk Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Mailer: Mozilla 4.04 [en] (Win95; I) Antony Arciuolo wrote: > Actually, I would be interested. I saw some stuff on circle collision, but > it involved squares and square roots that didn't seem that fast to me. > Please let me know if you have a quick algorithm. > > Thanks. > Yeah, that sounds like the usual circle collision detection.Here's a code snippet: // define radiuses of objects #define OBJ1_RADIUS 16 #define OBJ2_RADIUS 32 // define squared radiuses #define OBJ1_RADIUS2 OBJ1_RADIUS*OBJ1_RADIUS #define OBJ2_RADIUS2 OBJ2_RADIUS*OBJ2_RADIUS void check_collision(void) { int dx = obj1.x - obj2.x; // x distance between objects int dy = obj1.y - obj2.y; // y distance between objects if(dx*dx + dy*dy < OBJ1_RADIUS2+OBJ2_RADIUS2) { // we have a collision! } } The trick is to eliminate the need for any square roots. Why not just compare the squared values? Squaring takes very little processing time. Also, because the radiuses are constants, the squares and additions applied to them will be evaluated at compile time and won't take any processing time. So to detect a single collision, it only takes 2 subtractions, 2 multiplications, 1 addition and 1 comparison. Don't forget that for this to work right, your co-ordinates must point to the centre of the sprite rather than the lop-left corner as usual. Hope this helps. Herbs