Code: Select all
void NPC::searchPath(vector3df currentPos, s32 distance, int treeDepth, vector<line3d<f32>> pathPositions)
{
// We got to 0, so we're done searching in this part of our tree.
if (treeDepth == 0)
return;
// Else, recursion!
else
{
// For all angles (at the given interval of pathingAngleInterval, which is 20) around our current position.
// Note that the size of pathing angles should be 18 since 20 * 18 = 360.
for (int i = 0; i < pathingAngles.size(); i++)
{
// First we will find our new position based on the given distance at this ith angle.
vector3df tempPos;
tempPos.X = currentPos.X + (distance * sin( pathingAngles[i] * DEGTORAD));
tempPos.Z = currentPos.Z + (distance * cos( pathingAngles[i] * DEGTORAD));
// We do not have to worry about height for this search algorithm in our game, thank goodness!
tempPos.Y = target[0]->getTop().Y;
// Create a line from our current position to our newly created position.
line3d<f32> someLine(currentPos, tempPos);
vector3df collisionPoint;
// If we didn't hit anything...
if (!cmgr->getCollisionPoint(someLine, selector, collisionPoint, triangle3df()))
{
// Check to see if we can get to our target!
line3d<f32> lineToTarget(tempPos, target[0]->getTop());
vector3df collisionPoint2;
// Add this line to our vector of paths.
vector<line3d<f32>> newPathPositions = pathPositions;
newPathPositions.push_back(someLine);
// If we did get to our target successfully...
if(!cmgr->getCollisionPoint(lineToTarget, selector, collisionPoint2, triangle3df()))
{
// Add this vector to our vector of paths.
newPathPositions.push_back(lineToTarget);
// Now we are going to find out how long this path is.
int currentTotalDistance = 0;
for (int i = 0; i < newPathPositions.size(); i++)
{
currentTotalDistance += newPathPositions[i].getLength();
}
// If it's shorter than our shortest...
if ( currentTotalDistance < shortestPathingDistance)
{
// make this our new path and our new shortest distance.
this->pathPositions = newPathPositions;
shortestPathingDistance = currentTotalDistance;
}
// We could return true here if we wanted to just find a path, but
// we want to find the best path, so we will keep searching.
//return true;
}
// Else we hit something so keep searching for a new path
else
{
s32 newDistance = tempPos.getDistanceFrom(collisionPoint2);// - 3;
line3d<f32> line(tempPos, collisionPoint2);
vector<line3d<f32>> newPathPositions = pathPositions;
newPathPositions.push_back(line);
searchPath(collisionPoint2, newDistance, treeDepth - 1, newPathPositions);
}
}
// Else we hit something so keep searching for a new path.
else
{
s32 newDistance = currentPos.getDistanceFrom(collisionPoint);// - 3;
line3d<f32> line(currentPos, collisionPoint);
vector<line3d<f32>> newPathPositions = pathPositions;
newPathPositions.push_back(line);
searchPath(collisionPoint, newDistance, treeDepth - 1, newPathPositions);
}
}
return;
}
}Lastly, if anyone wants to rewrite this to an A* algorithm, I would worship you like a God forever