I'm trying to let an image follow a path. The points of this path are stored in an ArrayList. Right now the image jumps to the next point every two seconds, so I have to use linear interpolation to make the movement smooth. But how can I use linear interpolation in my update() method? I have a searched for this question on the net but couldn't find much information on linear interpolation in the update method in combination with an ArrayList with points.
Update method
public void update(){
repaint();
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);
pointOnTimeLine = new Point(startPoint);
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;
if (diff >= playTime) {
diff = playTime;
((Timer) e.getSource()).stop();
}
double i = (double) diff / (double) playTime;
pointInTime = i;
//pointOnTimeLine.x = (int) (startPoint.x + ((endPoint.x - startPoint.x) * i));
//pointOnTimeLine.y = (int) (startPoint.y + ((endPoint.y - startPoint.y) * i));
//carPosition.setLocation(pointOnTimeLine);
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 );
//System.out.println("Point"+pointOnTimeLine);
repaint();
counter++;
}
});
timer.start();
}
else{
//System.out.println("Destination reached");
}
//carPosition.x+=1;
//repaint();
}
double lerp(double a, double b, double t) {
return a + (b - a) * t;
}
Thread to move the car
public void moveCar() {
Runnable helloRunnable = new Runnable() {
public void run() {
car.update();
repaint();
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 40, TimeUnit.MILLISECONDS);
}
Lane.cs
public class Lane {
public static List<Point> firstLane = new ArrayList<>(Arrays.asList(new Point(10,135),new Point(124,190),new Point(363,190),new Point(469,210)));
}
EDIT: I have made changes to my code according to MadProgrammers suggestions. The animation works now here's the movie of the animation http://gyazo.com/e6a28b87cb905c0ff5eb023d68955321. My OP is updated with my current code. Next step is the turn part, but I think there is a more elegent way to call the car update method and repaint() in moveCar. I have specified the time in this thread to the same length as in the timer (40ms). Is there a better way to call car.update() and repaint in moveCar()?