I have a tile based engine and in the middle of translating out the example wall avoidance alogrithm in the book AI programming by example. I was wondering if the method below can be modified so that it takes a rectangle instead of vector C and D and still produce the same output ?
/-------------------- LineIntersection2D-------------------------
//
// Given 2 lines in 2D space AB, CD this returns true if an
// intersection occurs and sets dist to the distance the intersection
// occurs along AB. Also sets the 2d vector point to the point of
// intersection
//-----------------------------------------------------------------
inline bool LineIntersection2D(Vector2D A,
Vector2D B,
Vector2D C,
Vector2D D,
double& dist,
Vector2D& point)
{
double rTop = (A.y-C.y)*(D.x-C.x)-(A.x-C.x)*(D.y-C.y);
double rBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x);
double sTop = (A.y-C.y)*(B.x-A.x)-(A.x-C.x)*(B.y-A.y);
double sBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x);
if ( (rBot == 0) || (sBot == 0))
{
//lines are parallel
return false;
}
double r = rTop/rBot;
double s = sTop/sBot;
if( (r > 0) && (r < 1) && (s > 0) && (s < 1) )
{
dist = Vec2DDistance(A,B) * r;
point = A + r * (B - A);
return true;
}
else
{
dist = 0;
return false;
}
}