1

At the moment I have a simple animation where a car (JPanel) approaches a junction where after it waits for traffic lights to turn green and continues straight on. However I'm going to the next step now where I want the car to turn 90 deg right in a smooth curve to turn onto the perpendicular road. I have sketched roughly how it looks and the curve represent the way I want the car to turn:

Turning Car

I'm not too sure how to do this. I suppose I would need to represent some sort of bezier curve? Or matrix transformation to rotate the car?

Can someone give advice on the best way to do this in Swing.

Force444
  • 3,321
  • 9
  • 39
  • 77

1 Answers1

3

If you are new to graphics in Java, I recommend this tutorial. If I were to code what you are doing, I see two options.

First and easiest, you can model turning as "first driving straight, then turning 90º along the edge of a circle centred on the corner I am turning around, and then driving straight again". The easiest way to do this is to define a JPanel that draws your Image (yes, a JPanel; if you don't paint their background, you can layer JPanels on top of each other - and they will be painted in the correct order; make the background JPanel opaque so that it cleans up before drawing the next frame), and give it an AffineTransform that makes the image display in the position you want it to. You will need to adjust the increments in the transform so that the speed appears constant; trial and error, or a bit of geometry (90º of radius R implies R*pi/2.0 total travel along the curved path) , will help you out there.

The hard way is to consider the car's route to be an arbitrary Shape (which you can define using Bezier curves, for example), extract a flattened PathIterator from it, advance in equally-spaced jumps along that iterator, and calculate the rotation you need from the position along the curve and the heading at any given point (you can estimate the heading by taking 2 successive samples, and aligning the car according to these samples). This is harder than using the above method, but allows your car to follow arbitrarily complex paths.

tucuxi
  • 17,561
  • 2
  • 43
  • 74
  • 1
    See also [`CircleTest`](http://stackoverflow.com/a/2510048/230513) and [`RotateApp`](http://stackoverflow.com/a/3420651/230513). – trashgod Nov 25 '12 at 14:42