Page 1 of 1

Seperating Axis Theorem troubles

Posted: Fri Dec 17, 2010 10:04 pm
by cndr
I've been following an article at http://www.gamedev.net/reference/progra ... /page2.asp. I've read through the article a bunch of times and wrote out what I understood in code, I'm not sure if I'm misinterpreting something, but my code always returns a collision. any one know what I did wrong?

Code: Select all

#include <iostream>
using namespace std;
int main()
{
struct coordinates {float x; float y; float z; float w; float h; float d;};
coordinates coord_a = {2,6,0, 2,2,0};
coordinates coord_b = {0,0,0,   1,1,0};
coordinates axis[4];
coordinates rect[2][4];

float temp[3];
float scalar[4][2][4];
float minmax[4][2][2];//axis,rect,min/max

#define UR 0
#define UL 1
#define LL 2
#define LR 3

rect[0][UR].x = coord_a.x+coord_a.w; //UR
rect[0][UR].y = coord_a.y;
rect[0][UL].x = coord_a.x; //UL
rect[0][UL].y = coord_a.y;
rect[0][LL].x = coord_a.x;  //LL
rect[0][LL].y = coord_a.y+coord_a.h;
rect[0][LR].x = coord_a.x+coord_a.w; //LR
rect[0][LR].y = coord_a.y+coord_a.h;

rect[1][UR].x = coord_b.x+coord_b.w; //UR
rect[1][UR].y = coord_b.y;
rect[1][UL].x = coord_b.x; //UL
rect[1][UL].y = coord_b.y;
rect[1][LL].x = coord_b.x; //LL
rect[1][LL].y = coord_b.y+coord_b.h;
rect[1][LR].x = coord_b.x+coord_b.w; //LR
rect[1][LR].y = coord_b.y+coord_b.h;

axis[0].x = rect[0][UR].x - rect[0][UL].x;
axis[0].y = rect[0][UR].y - rect[0][UL].y;
axis[1].x = rect[0][UR].x - rect[0][LR].x;
axis[1].y = rect[0][UR].y - rect[0][LR].y;
axis[2].x = rect[1][UL].x - rect[1][LL].x;
axis[2].y = rect[1][UL].y - rect[1][LL].y;
axis[3].x = rect[1][UL].x - rect[1][UR].x;
axis[3].y = rect[1][UL].y - rect[1][UR].y;

for (int i=0; i<4; i++) //axis
{
	for (int j=0; j<2; j++) // rect
	{
		for (int k=0; k<4; k++) //vector
		{
		temp[0] = (rect[j][k].x * axis[i].x + rect[j][k].y * axis[i].y)/((axis[i].x*axis[i].x)+(axis[i].y*axis[i].y));
		temp[1] = temp[0]*axis[i].x;
		temp[2] = temp[0]*axis[i].y;

		scalar[i][j][k] = (temp[1] * axis[i].x) + (temp[2] * axis[i].y);
		}
	}
}

for (int i=0; i<4;i++)
{
	for (int j=0; j<2; j++)
	{
	minmax[i][j][0] = 99999999;
	minmax[i][j][1] = -99999999;
	}
}

for (int i=0; i<4; i++) //axis
{
	for (int j=0; j<2; j++) // rect
	{
		for (int k=0; k<4; k++) //vector
		{
			if (scalar[i][j][k] < minmax[i][j][0])
			{
			minmax[i][j][0] = scalar[i][j][k];
			}
			if (scalar[i][j][k] > minmax[i][j][1])
			{
			minmax[i][j][1] = scalar[i][j][k];
			}
		}
	}
}

for (int i=0; i<4; i++)
{

	if (minmax[i][1][0] <= minmax[i][0][1] || minmax[i][1][1] >= minmax[i][0][0])
	{
	cout << "collision: "<< i <<endl;
	}
	else 
	{
	cout << "No Collision"<<endl;
	break;
	}
}

return 0;
}

Re: Seperating Axis Theorem troubles

Posted: Sat Dec 18, 2010 2:23 am
by Milch

Re: Seperating Axis Theorem troubles

Posted: Sat Dec 18, 2010 7:22 pm
by cndr
thanks for the help, will take a look at it.