为什么我的布雷森汉姆线算法使我的程序崩溃

本文关键字:我的 程序 崩溃 算法 布雷森 为什么 | 更新日期: 2023-09-27 18:26:45

我一直在尝试创建一个Bresenhams线算法来保持顺序,以便用户能够在运行时在网格上绘制。

在大多数情况下,它有效,但是,它似乎卡在一段时间循环中并偶尔使我的程序崩溃。我相信这是鼠标移动得非常快的时候。

public static IEnumerable<WorldTile> GetWorldTilesOnLine(int x0, int y0, int x1, int y1)
{
    int dy = (int)(y1-y0);
    int dx = (int)(x1-x0);
    int xstep = 1;
    int ystep = 1;
    if (dy < 0) {dy = -dy; xstep = -1;}
    else {ystep = 1;}
    if (dx < 0) {dx = -dx; ystep = -1;}
    else {xstep = 1;}
    dy <<= 1;
    dx <<= 1;
    float fraction = 0;
    //Debug.Log (xstep);
    if (x0 >= 0 && x0 < worldBoard.GetLength(0) && y0 >= 0 && y0 <  worldBoard.GetLength(1))
    {
        yield return worldBoard[x0, y0];
    }
    if (dx > dy) {
        fraction = dy - (dx >> 1);
        while (Mathf.Abs(x0 - x1) > 1) { // This seems to be where the crash occurs
            if (fraction >= 0) {
                y0 += ystep;
                fraction -= dx;
            }
            x0 += xstep;
            fraction += dy;
            if (x0 >= 0 && x0 < worldBoard.GetLength(0) && y0 >= 0 && y0 < worldBoard.GetLength(1))
            {
                yield return worldBoard[x0, y0];
            }
        }
    }
    else {
        fraction = dx - (dy >> 1);
        while (Mathf.Abs(y0 - y1) > 1) { // This seems to be where the crash occurs
            if (fraction >= 0) {
                x0 += xstep;
                fraction -= dy;
            }
            y0 += ystep;
            fraction += dx;
            if (x0 >= 0 && x0 < worldBoard.GetLength(0) && y0 >= 0 && y0 < worldBoard.GetLength(1))
            {
                yield return worldBoard[x0, y0];
            }
        }
    }
    yield break;
}
当用户

按下鼠标按钮时调用此方法

IEnumerator Draw()
{
    startPos =  WorldGridUtilities.getNearestWorldTileArrayValue(getMousePosition());
    worldTilesToAdd = new List<WorldTile>();
    Debug.Log (worldTilesToAdd.Count);
    while (true)
    {       
        worldTilesToAdd.Clear();
        nextPos = WorldGridUtilities.getNearestWorldTileArrayValue(getMousePosition());
        if (nextPos != startPos)
        {
            foreach (WorldTile wt in WorldGridUtilities.GetWorldTilesOnLine((int)startPos.x,(int)startPos.y, (int)nextPos.x, (int)nextPos.y))
            {
                worldTilesToAdd.Add (wt);
            startPos = nextPos;
        }
        foreach (WorldTile wt in worldTilesToAdd)
        {
            //Debug.Log ("coordinates added to list used by vectorline: " + wt.gridCoordinates);
            vectorLine.points3.Add(wt.gridCoordinates);
            vectorLine.Draw3D();
        }

        yield return new WaitForEndOfFrame();
    }
}

为什么我的布雷森汉姆线算法使我的程序崩溃

xstep ystep有些奇怪。如果dy > 0dx < 0,则xstep = 1ystep = 1.所以x1 < x0因为dx < 0但你不断增加 x0 与xstep =1.这意味着无限循环。可能某些内容过载,有时您会收到错误。