2012-04-15 51 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

你应该认识到哟你不是在进行体积碰撞,而是在线碰撞,如果船舶或角色或任何在源位置的物体可能需要增加更多的计算值