Skip to main content
gamedev.net
🔒 Locked

my rectangle collision code

Started by Joel_h 3 replies 150+ views
Original Post
Joel_h
Joel_h
Hello, I had some trouble finding code and articles on checking rectangle collisions, I spent alot of time looking for the best way to do it and I''ve made a simple function to check if two RECTs are overlapping. If anybody doesn''t know how or wants simply wants a function that does it that they can just put in their code you can use this. It returns 1 if they''re overlapping and 0 if they''re not.
  
int Colision_Rects(RECT r1,RECT r2);

int Colision_Rects(RECT r1,RECT r2)
{		// this takes 2 rects and returns 1 if they''re touching 0 if they''re not



	// bottom left corner

	if (((r1.bottom < r2.bottom)&&(r1.left > r2.left))&&((r1.bottom>r2.top)&&(r1.left<r2.right)))
	{
	return 1;
	}

	// top left corner

	if (((r1.top > r2.top)&&(r1.left > r2.left))&&((r1.top < r2.bottom)&&(r1.left<r2.right)))
	{
		return 1;
	}

	// bottom right corner

	if (((r1.bottom < r2.bottom)&&(r1.right < r2.right))&&((r1.bottom > r2.top)&&(r1.right>r2.left)))
	{
		return 1;
	}
	//top right corner

	if (((r1.top > r2.top)&&(r1.right < r2.right))&&((r1.top < r2.bottom)&&(r1.right>r2.left)))
	{
		return 1;
	}

	////////////////////////////////////

	// we have to do it for #2 now

		// bottom left corner

	if (((r2.bottom < r1.bottom)&&(r2.left > r1.left))&&((r2.bottom>r1.top)&&(r2.left<r1.right)))
	{
	return 1;
	}

	// top left corner

	if (((r2.top > r1.top)&&(r2.left > r1.left))&&((r2.top < r1.bottom)&&(r2.left<r1.right)))
	{
		return 1;
	}

	// bottom right corner

	if (((r2.bottom < r1.bottom)&&(r2.right < r1.right))&&((r2.bottom > r1.top)&&(r2.right>r1.left)))
	{
		return 1;
	}
	//top right corner

	if (((r2.top > r1.top)&&(r2.right < r1.right))&&((r2.top < r1.bottom)&&(r2.right>r1.left)))
	{
		return 1;
	}

	// if no verticies inside


	if ((r2.top > r1.top)&&(r2.bottom < r1.bottom)&&(r2.left < r1.left)&&(r2.right>r1.right))
	{
		return 1;
	}


	if ((r1.top > r2.top)&&(r1.bottom < r2.bottom)&&(r1.left < r2.left)&&(r1.right>r2.right))
	{
		return 1;
	}
	return 0;
}
  
m00se123
m00se123
thats good, but there is a much simpler way of doing it. there are more ways the boxs can overlap then they cannot, so why don''t you instead test if they don''t collide. here is the code i use. it returns 0 if the boxs don''t collide, otherwise it returns 1. also you wouldnt need to use classes if you don''t want to, just organizes it more.

class bbox
{
public:
int top,bottom,left,right;
};

int BBCD(bbox b1, bbox b2)
{

if(b1.left > b2.right) return 0;
if(b1.right < b2.left) return 0;
if(b1.top > b2.bottom) return 0;
if(b1.bottom < b2.top) return 0;

return 1;
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.