2015-03-31 54 views
0

我有一个名为moveCar的方法,它有一个每40毫秒调用一次car.update()方法的计时器。在目前的情况下,计数器每40毫秒增加一次,但计数器只能在汽车在终点时增加。然后计数器应该增加(这意味着终点现在是列表中的下一个点),并且应该随着lineair插值移动到下一个点,这应该发生,直到达到最后一个点。我试图检查更新方法,如果汽车位置等于终点位置,计数器增加但它没有解决问题,如何做到这一点?带点的线性插值列表

的moveCar方法:

 public void moveCar() { 
      Timer timer = new Timer(40, new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (startTime == null) { 
        startTime = System.currentTimeMillis(); 
       } 
       long now = System.currentTimeMillis(); 
       long diff = now - startTime; 

       i = (double) diff/(double) playTime; 

       car.update(i);         
       repaint(); 

      } 
     }); 
     timer.start(); 
     } 

车更新+线性插值方法:

public void update(double i){ 

     repaint(); 

     //counter is 0 by default 

     if (counter < Lane.firstLane.size()) { 

      startPoint = new Point(carPosition.x, carPosition.y); 
      endPoint = new Point(Lane.firstLane.get(counter).x, Lane.firstLane.get(counter).y); 

      carPosition.x=(int)lerp(startPoint.x,endPoint.x,i);     
      carPosition.y=(int)lerp(startPoint.y,endPoint.y,i);          

      System.out.println("Car position: x" + carPosition.x + ": y" + carPosition.y); 
      repaint(); 

      counter++; 
     } 
} 



    double lerp(double a, double b, double t) { 
      return a + (b - a) * t; 
     } 

Lane.cs

  public static List<Point> firstLane = new ArrayList<>(Arrays.asList(new Point(10,375),new Point(215,385),new Point(230,452)/*,new Point(531,200)*/)); 
+0

那么,问题是什么?我很难区分“应该”与实际的错误描述... – Seb 2015-03-31 15:01:10

+0

问题是:计数器在当前情况下每40毫秒更新一次,只有当汽车处于最终位置时才会增加。随着计数器的增加,endPosition也会更新,如代码中所示。 – Sybren 2015-03-31 15:04:27

+0

我认为你的'if(...)'在这种情况下更新方法总是正确的。这就是为什么柜台总是增加。顺便说一句,将代码缩小到一个最小的例子会使得提供反馈更容易。 – Seb 2015-03-31 15:10:41

回答

0

我会假设你的更新方法是错误的

Lane currentLane = ...; // store the current lane somewhere 
Lane nextLane = ...; // store the next lane somewhere 

public void update(double progress){ 
    startPoint = new Point(currentLane.x, currentLane.y); 
    endPoint = new Point(nextLane.x, nextLane.y); 

    carPosition.x=(int)lerp(startPoint.x, endPoint.x, progress);     
    carPosition.y=(int)lerp(startPoint.y, endPoint.y, progress);          

    if (progress >= 1.0) { /// assuming that 0 <= progress <= 1 
     currentLane = nextLane; 
     nextLane = ...; // switch next lane 
    } 
} 

我删除了repaint()调用...我想你需要将它们包含在适当的位置。我的代码不适用于第一个Lane(或最后一个,取决于您的实现)。我仍然不太清楚这个问题,所以很难解决。 :)

+0

我不太了解你的解决方案。你有一个nextLane宣布,但车必须留在一个车道(也许我后来实现多车道),存在多个点。我的例子中也没有看到柜台。计数器需要指向Lane列表中的一个点。 – Sybren 2015-03-31 18:01:05