Need Help With Determinig A Formula
Posted: Fri Nov 14, 2008 6:01 pm
What formula could i use if i wanted to determine if a single point landed inside a set of points (i.e., triangle or circle)?
The Next Generation of 2D Roleplaying Games
http://elysianshadows.com/phpBB3/
Code: Select all
+-----+
| . |
+-----+
EDIT: this code works for any geometry. skew lines and so on.I_Mystic_I wrote:What formula could i use if i wanted to determine if a single point landed inside a set of points (i.e., triangle or circle)?
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;
}