I'm doing a simulation program in Scala and I'm trying to render the simulation in a JPanel by overriding the paintComponent:
override def paintComponent(g: Graphics2D) = {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paintComponent(g)
tx1 = g.getTransform()
g.setColor(new Color(0,0,0))
simulator.getVehicles foreach{vehc =>
g.translate(vehc.getPos.x,vehc.getPos.y)
g.draw(new Ellipse2D.Double(-Vehicle.rad, -Vehicle.rad, Vehicle.diam, Vehicle.diam))
g.drawLine(0,0,(Vehicle.rad*vehc.getDir.x).toInt,(Vehicle.rad*vehc.getDir.y).toInt)
g.setTransform(tx1)
}
}
I have the simulation itself running on a different thread:
def run{
//logic loop
time = System.currentTimeMillis();
dt = 1000/60
while(loop)
{
getVehicles.foreach{
_.move
}
collider.solvecollisions()
Thread.sleep(dt- (time - System.currentTimeMillis()))
time = System.currentTimeMillis();
}}
GetVehicles returns a Buffer[Vehicle] of all simulated vehicles.
My problem is that there is jittering in the rendering. What I mean is that sometimes some of the vehicles are rendered a timestep later than others. I presume this happens because the simulation loop updates the positions at the same time the render loop fetches the positions, and there is some overlap. i.e. when rendering begins in timestep n,half of the vehicles are rendered and then timestep n+1 happens and the rest of the vehicles are rendered a timestep further. First I thought this was a problem to be solved with double buffering, but since paintComponent already does that, I dont think thats the case. Any ideas how to fix this? I tried simply rendering getVehicles.clone but that didn't help because the references to the vehicles are still the same.
Thanks!