2015-03-31 62 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