提问者:小点点

带点的线性插值表


我有一个名为moveCar的方法,它有一个定时器,每40毫秒调用car. update()方法。在当前情况下,计数器每40毫秒递增一次,但只有当汽车在终端时,计数器才应该递增。然后计数器应该递增(这意味着endpoint现在是列表中的下一个点),并且应该通过lineair插值移动到下一个点,直到到达最后一点。我试图在update方法中检查,如果汽车位置等于计数器递增的结束位置,但它没有解决问题,如何做到这一点?

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();
        }

汽车更新lerp方法:

 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)*/));

共1个答案

匿名用户

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

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(或最后一个Lane,取决于您的实现)。我仍然不太明白问题,所以很难修复。:)