2012-04-15 49 views
1

你好我是XNA的新手,並試圖開發一個遊戲原型,其中角色使用鼠標點擊從一個位置移動到另一個位置。矩形中包含的XNA Vector2路徑

我有一個Rectangle表示當前位置。我使用播放器鼠標輸入將目標位置作爲Vector2。我通過Vector2減法從源向目標提取方向矢量。

//the cursor's coordinates should be the center of the target position 
float x = mouseState.X - this.position.Width/2; 
float y = mouseState.Y - this.position.Height/2; 
Vector2 targetVector = new Vector2(x, y); 
Vector2 dir = (targetVector - this.Center); //vector from source center to target 
              //center 

我代表世界使用瓷磚地圖,每個單元格是32x32像素。

int tileMap[,]; 

我想要做的是檢查上面的方向矢量是否通過地圖上的任何藍色瓷磚。地圖上的藍色小方塊等於1。

我不知道如何做到這一點。我想過使用線性直線方程和三角函數公式,但我發現很難實現。我已經嘗試了使矢量正​​常化並乘以32以獲得沿着矢量路徑的32個像素長度的間隔,但它似乎不起作用。任何人都可以告訴我它是否有任何問題,或者解決這個問題的另一種方法?由於

//collision with blue wall. Returns point of impact 
    private bool CheckCollisionWithBlue(Vector2 dir) 
    { 
     int num = Worldmap.size; //32 
     int i = 0; 
     int intervals = (int)(dir.Length()/num + 1); //the number of 32-pixel length 
                 //inervals on the vector, with an edge 
     Vector2 unit = Vector2.Normalize(dir) * num; //a vector of length 32 in the same 
                 //direction as dir. 
     Vector2 v = unit; 
     while (i <= intervals & false) 
     { 
      int x = (int)(v.X/num); 
      int y = (int)(v.Y/num); 
      int type = Worldmap.getType(y, x); 
      if (type == 1) //blue tile 
      { 
       return true; 
      } 
      else 
      { 
       i++; 
       v = unit * i; 
      } 
     } 
     return false; 
    } 

回答

1
  1. 您需要的初始現在的位置也是如此,不僅方向
  2. 也許你需要更高的分辨率
  3. ¿什麼?去掉「假」的評價
  4. 明年POS Calcs(計算)是一個有點複雜

private bool CheckCollisionWithBlue(Vector2 source, Vector2 dir) 
{ 
    int num = 8; // pixel blocks of 8 
    int i = 0; 
    int intervals = (int)(dir.Length()/num); 

    Vector2 step = Vector2.Normalize(dir)*num; 

    while (i <= intervals) 
    { 
     int x = (int)(source.X); 
     int y = (int)(source.Y); 
     int type = Worldmap.getType(y, x); 
     if (type == 1) //blue tile 
     { 
      return true; 
     } 
     else 
     { 
      i++; 
      source+=step; 
     } 
    } 
    return false; 
} 

這將提高一些代碼,但也許innacurate ...這取決於你有什麼做...

你也許可以發現,有趣的Bresenham直線算法http://en.wikipedia.org/wiki/Bresenham「s_line_algorithm

你應該認識到喲你不是在進行體積碰撞,而是在線碰撞,如果船舶或角色或任何在源位置的物體可能需要增加更多的計算值