2015-12-14 75 views
-1

我一直在嘗試創建一個Bresenhams線算法,它可以保留順序,以便用戶能夠在運行時在網格上繪圖。爲什麼我的Bresenhams行算法崩潰我的程序?

它的作用大部分,但是,它似乎陷入了一個while循環並偶爾崩潰我的程序。我相信這是鼠標移動速度非常快的時候。

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(); 
    } 
} 
+1

你有一個確切的聲明,它崩潰? – FKutsche

+0

不,我很抱歉,我沒有。它崩潰了Unity,我沒有收到任何錯誤消息。我知道它在while循環中崩潰的唯一原因是當我嘗試打印日誌時,它會在到達該點之前停止。 – Jim

+0

是否有可能您列出或vectorLine變得太大? – FKutsche

回答

1

有什麼東西在XSTEP ystep奇怪這個方法被調用。 if dy > 0 and dx < 0 then xstep = 1 and ystep = 1。 因此x1 < x0因爲dx < 0但您繼續增加x0與xstep =1。這意味着無限循環。可能有些東西會超載,有時會出現錯誤。

相關問題