When I was using XNA, I wrote a genericized A* pathfinding system for a project. It was comprised of an interface iPathable and a class Pathfinder. iPathable had functions for finding neighbors and calculating heuristic costs. Pathfinder’s primary feature was a function that returned a List, where T was iPathable.
But in Unity I’m struggling to wrap my mind around the problem as a component based solution. I have a battlefield composed of hexes. Each hex has a script attached to it that contains its X and Y values. It wouldn’t be hard to just write the methods contained in iPathable as non-generic methods in the hex script. But if, in theory, I had a battlefield comprised of hexes and other shapes, that wouldn’t work, because Pathfinder would have to be rewritten to return a List.
Can’t you just have Hex and OtherShape both implement iPathable? Then they should count as iPathables (and can be returned in a List). They can still implement their own ‘next in line’ solutions.
class Hex implements iPathable {
function GetPath() {
for ( pathable in AllPathables ) {
if ( pathable.GetDistanceFrom() )....
Let each class define its own distance/etc functions; don’t try to access member variables of pathables that aren’t “this”.
Yes, you can do this. In this example, you are deriving from one class, and implementing one interface. You can derive from only one class, but you can implement many interfaces.
One suggestion: Would it be better overall to create a separate class which contains the shape gameobjects, and also contains the path implementation for that shape?
class PathStep
{
private readonly GameObject _pathGo;
private readonly ShapeLogic _pathLogic;
private GameObject PathGO;
private ShapeLogic PathLogic;
public PathStep(GameObject pathGo, ShapeLogic pathLogic)
{
_pathGo = pathGo;
_pathLogic = pathLogic;
}
public float PathCost(...)
{
return _pathLogic.PathCost(...whatever goes here);
}
}
// Shapelogic would handle the logic for different shapes, as far as pathing goes. Like a circle, vs a hex, vs a square.
//Path controller would handle returning pathing results, and also would initialize to hold all pathable locations.
internal class PathController
{
// Initialize the internal data from the shapes in the world.
// All pathable gameobjects might be children of one gameobject, and this
// would initialize its internal information from that parent.
// Call this to get the path steps from point a to b
private List<PathStep> GetPath(PathStep startPath, PathStep endPath)
{
return new List<PathStep>();// return the actual path steps here.
}
}
This may totally not work for you, though. I haven’t done any pathfinding (yet) But it might keep you from having to include your path logic in with your gameobjects (maybe a big deal, maybe not).