A*在多个网格上寻路

Cai*_*ene 10 c# path-finding unity-game-engine

我试图围绕一个立方体实现A*寻路,立方体由6个网格组成,为​​了保持简单,我有4种方法GetXPlus,GetXMinus,GetYPlus,GetYMinus.每个方法检查下一个tile是否在当前网格空间内,如果它不是切换到适当的网格.

我遇到的问题是当试图从当前网格中另一个方向翻转的网格中获取一个图块时,返回的图块位于另一侧.是否有一种方法或方法可以避免为每个原始网格和方向编写独特的逻辑?

为了帮助清楚地表达我的问题,在这里,我来自(紫色)网格,并使用GetXPlus方法:

在此输入图像描述

我当前实现的一个snippit(每个网格是64乘64):

public Tile GetXPlus( int currentX, int currentY )
{
    var newX = currentX + 1;
    var tile = GetTile( newX , currentY );

    if( newX > 64 ) //Get adjacent XPlus Grid 
    { 
        currentGrid = SetCurrentGrid( XPlusGridIndex );
        tile = GetTile( newX - 64, currentY );
    }

    return tile;
}
Run Code Online (Sandbox Code Playgroud)

背景

此实现源于对此处建议的不同问题的出色答案:https://gamedev.stackexchange.com/questions/53866/pathfinding-on-a-uneven-planetary-surface

Til*_*ilo 0

您可以使用函数将由“X 坐标”、“Y 坐标”和“平铺”组成的一个 3D 坐标空间映射到另一个 3D 坐标空间。

给定一个命令:

enum TileBorder
{
    Left   = 0,
    Top    = 1,
    Right  = 2,
    Bottom = 3
}
Run Code Online (Sandbox Code Playgroud)

您可以将这些转换存储在您的Tile类的数组中:

class Tile
{
    public Tile[] Neighbors { get; set; }
    public Func<int, int, int>[] XTransitions { get; set; }
    public Func<int, int, int>[] YTransitions { get; set; }

    public void GetXPlus(int x, int y, out int newX, out int newY, out Tile newTile)
    {
        x++;
        if (x <= 64)
        {
            newX = x;
            newY = y;
            newTile = this;
        }
        else
        {
            newX = XTransitions[(int)TileBorder.Right](x, y);
            newY = YTransitions[(int)TileBorder.Right](x, y);
            newTile = Neighbors[(int)TileBorder.Right];
        }
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

那么你只需要在设置结构的时候稍微注意一下就可以了。例如,假设坐标从 1 到 64(包含 1 和 64),这就是设置绿色图块的方法。

Tile pink   = new Tile();
Tile green  = new Tile();
Tile orange = new Tile();
Tile purple = new Tile();
Tile blue   = new Tile();

green.Neighbors = new Tile[] 
{ 
    /* left */   orange, 
    /* top */    pink,
    /* right */  blue,
    /* bottom */ purple 
};

green.XTransitions = new Func<int, int, int>[] 
{
    /* left */   (x, y) => 1, 
    /* top */    (x, y) => x,
    /* right */  (x, y) => 64,
    /* bottom */ (x, y) => x 
};

green.YTransitions = new Func<int, int, int>[] 
{
    /* left */   (x, y) => 65 - y, 
    /* top */    (x, y) => 64,
    /* right */  (x, y) => 65 - y,
    /* bottom */ (x, y) => 1
};
Run Code Online (Sandbox Code Playgroud)

请注意,图块转换函数只是一个查找,但为了完全灵活,您还可以使用以下类型的函数:
Func<int, int, Tile, int>x 坐标、
Func<int, int, Tile, int>y 坐标和
Func<int, int, Tile, Tile>图块。