Java:在路径上移动的对象,忽略某些坐标。怎么修?

时间:2012-11-28 17:55:12

标签: java

我有一个从A点移动到随机点B的圆圈。当物体接近B点时,会选择一个新的随机目标位置。如果圆圈平行于X轴或Y轴移动,则物体会穿过所有像素并留下实线。但如果圆圈沿对角方向移动,它会跳过像素并轻微抖动,使动画不平滑并留下带有未上漆像素的痕迹。

我的算法是:

  1. 计算X和Y距离
  2. 检查圈子是否在附近
  3. 如果是,请选择新目的地
  4. 如果2.为真,请使用毕达哥拉斯'找到真正的距离。定理
  5. 如果2.为真,则计算X和Y速度(坐标的变化)
  6. 设置新坐标(无论是否为真)
  7. 以下是代码:

      public void move ()//движение
      {
          //finds the X and Y distance to the destination
          int triangleX = nextLocationX - coorX;
          int triangleY = nextLocationY - coorY;
          //if too near the coordinates of the destination changes
          if (Math.abs(triangleX) <= Math.abs(speedX) || Math.abs(triangleY) <= Math.abs(speedY))//setting the new target
          {
              //setting the new destinatio
              int randInt;
              for (;;)//I don't want the the new destination to be that same spot
              {
                  randInt= randGen.nextInt(appletX);
                  if (randInt != nextLocationX)
                  {
                      nextLocationX = randInt + radius;
                      break;
                  }
              }
              for (;;)
              {
                  randInt = randGen.nextInt(appletY);
                  if (randInt != nextLocationY)
                  {
                      nextLocationY = randInt + radius;
                      break;
                  }
              }
              //calculating the change of the circle's X and Y coordinates
              triangleX = nextLocationX - coorX;
              triangleY = nextLocationY - coorY;
              speedX = ((double)(speed * triangleX) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
              speedY = ((double)(speed * triangleY) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
          }
          //the realCoor variables are from type double
          //they are the exact coordinates of the circle
          //If I only use integers, the circle almost
          //never reaches it's destination
          //unless the change of the coordinates gets calculated
          //after every time they change
          realCoorX = realCoorX + speedX;
          realCoorY = realCoorY + speedY;
          coorX = (int)Math.round(realCoorX);
          coorY = (int)Math.round(realCoorY);
      }
    

    我怀疑问题在于计算坐标的变化。

1 个答案:

答案 0 :(得分:0)

对我而言,这听起来像是一个别名问题。如果绘制(!)与坐标轴不对齐的线,则会出现同样的问题。如您所知,即对角线需要“半满”像素才能看起来光滑。

您将使用浮点位置计算(取决于渲染技术)。