找到C中2点之间的直线

时间:2016-07-11 16:11:11

标签: c math logic

尝试制作游戏,我需要实体从其当前位置寻找直线到另一个点。我目前有以下代码:

void pathfind_test(path_data my_path[], int *path_to, double *x, double *y)
//path_data just has a column and a row (grid co-ordinates in the game)
//path_to is the array index to pathfind to
//x and y are the entities coordinates

{
  my_path += *path_to;
  int path_to_x = my_path->col * 60 - 30;
  int path_to_y = my_path->row * 60 - 30;
  //converts grid co-ordinates to X,Y co-ordinates
  double rise = path_to_y - *y;
  double run = path_to_x - *x;
  double grad = sqrt(rise * rise + run * run);

  if ((rise != 0) && (run != 0))
  {
    *y = *y + (rise / grad);
    *x = *x + (run / grad);
  }
  else
  {
    if (path_to_x > *x) {*x = *x + 1;}
    if (path_to_x < *x) {*x = *x - 1;}
    if (path_to_y > *y) {*y = *y + 1;}
    if (path_to_y < *y) {*y = *y - 1;}
  }

  if ((path_to_y == *y) && (path_to_x == *x)) {*path_to += 1;}
  if (*path_to == 40)
  {
    *x = 1200;
    *y = 150;
    *path_to = 0;
  }
}

但是当实体进入像素距离时,它会在现场震动并且实际上从未达到真正的X,Y坐标。

虽然旅行也不是一个平稳的旅行,它有点摇摇欲坠。

我认为我的变量没有得到足够精确的数字来追踪最后一点点的数字,所以我认为这段代码会有所帮助,但它会让实体传送也支持我的理论,即价值不是'足够精确:

if ((rise / grad) + (run / grad) < 1)
{
  *x = path_to_x;
  *y = path_to_y;
}
else
{
  *y = *y + (rise / grad);
  *x = *x + (run / grad);
}

Dunno如何修复此逻辑并使其在x,y co-ords之间平滑过渡。

0 个答案:

没有答案