Page 1 of 1

Some vector equations i coudent find when i was starting.

Posted: Sun Nov 02, 2008 6:41 pm
by avansc
hi, just recently joined. so just thought id offer something to the forum.
i remember when i started game development i struggled to get collision code for line vs line and so on.

ps: it was commented, but not in english, so i just took it out.
line is just a class with, x1, y1, x2, y2, variables. its just the 2 end points of the line.
the equations are not optimized, but are pretty fast. Oh, and SimCol was the class name that i used the equations is.
so it wont work if you copy past it. but im sure you can figure it out.

hope this helps some one.

let me know if you have any questions.=

Code: Select all


bool SimCol::pointInSphere(float sX, float sY, float sR, float x, float y)
{
	float dist = (sX - x)*(sX - x) + (sY - y)*(sY - y);
	if(dist < sR*sR)
		return true;
	return false;
}

bool SimCol::lineInter(line &AB, line &CD)
{
	if(((CD.y2 - CD.y1)*(AB.x2 - AB.x1) - (CD.x2 - CD.x1)*(AB.y2 - AB.y1)) == 0)
		return false;

	if(((CD.y2 - CD.y1)*(AB.x2 - AB.x1) - (CD.x2 - CD.x1)*(AB.y2 - AB.y1)) != 0)
	{
		if(((((CD.x2 - CD.x1)*(AB.y1 - CD.y1) - (CD.y2 - CD.y1)*(AB.x1 - CD.x1))/
				((CD.y2 - CD.y1)*(AB.x2 - AB.x1) - (CD.x2 - CD.x1)*(AB.y2 - AB.y1))) > 0) && ((((CD.x2 - CD.x1)*(AB.y1 - CD.y1) - (CD.y2 - CD.y1)*(AB.x1 - CD.x1))/
				((CD.y2 - CD.y1)*(AB.x2 - AB.x1) - (CD.x2 - CD.x1)*(AB.y2 - AB.y1))) < 1))
		{
			if((((AB.x2 - AB.x1)*(AB.y1 - CD.y1) - (AB.y2 - AB.y1)*(AB.x1 - CD.x1))/
				((CD.y2 - CD.y1)*(AB.x2 - AB.x1) - (CD.x2 - CD.x1)*(AB.y2 - AB.y1)) > 0) && (((AB.x2 - AB.x1)*(AB.y1 - CD.y1) - (AB.y2 - AB.y1)*(AB.x1 - CD.x1))/
				((CD.y2 - CD.y1)*(AB.x2 - AB.x1) - (CD.x2 - CD.x1)*(AB.y2 - AB.y1)) < 1))
			{
				return true;
			}
		}
	}

	return false;
}

bool SimCol::lineInSphere(float sX, float sY, float sR, line &AB)
{
	if(this->pointInSphere(sX, sY, sR, AB.x1, AB.y1))
		return true;
	if(this->pointInSphere(sX, sY, sR, AB.x2, AB.y2))
		return true;

	float dx = AB.x2 - AB.x1;
	float dy = AB.y2 - AB.y1;
	float d = dx*dx + dy*dy;
	float D = (AB.x1 - sX)*(AB.y2 - sY) - (AB.x2 - sX)*(AB.y1 - sY);
	float delta = ((sR*sR) * d) - (D*D);

	float sgn = 0;
	float dyP = dy;

	if(dyP<0)
		dyP = -1 *dyP;

	if(dy < 0)
	{
		sgn = -1;
	}else{
		sgn = 1;
	}

	if(((sR*sR) * (((AB.x2 - AB.x1)*(AB.x2 - AB.x1)) + ((AB.y2 - AB.y1)*(AB.y2 - AB.y1)))) - (((AB.x1 - sX)*(AB.y2 - sY) - (AB.x2 - sX)*(AB.y1 - sY))*((AB.x1 - sX)*(AB.y2 - sY) - (AB.x2 - sX)*(AB.y1 - sY))) >= 1)
	{
		if(((D*dy + sgn * dx * sqrt(sR*sR*d - D*D)) / d) >= AB.x1 && ((D*dy + sgn * dx * sqrt(sR*sR*d - D*D)) / d) <= AB.x2)
			return true;
		if(((D*dy + sgn * dx * sqrt(sR*sR*d - D*D)) / d) >= AB.x2 && ((D*dy + sgn * dx * sqrt(sR*sR*d - D*D)) / d) <= AB.x1)
			return true;
	}

	return false;
}