Okay so I have an ellipse and I could like to have a "racecar" (actually just a 10x10 rectangle) follow the ellipse around the edge. The point that is always touching the ellipse is the upper left hand corner of the "racecar." I'm not even sure where to begin writing this code. I want to make it move a random distance along the edge of the ellipse. so i guess the code could look something like this:

``````while(!raceOver)
{
car.moveRandomDistance();
repaint();
waitSomeTime(500);
}``````

This is a thread so this would be inside the run() method and also inside try{}catch{}

The only advice I got was to use angles and to update the angle each loop but not sure about that.

Any help would be awesome. Thanks.

- the waitSomeTime() is simply made into a method in order to synchronize the methods and ensure one finishes before moving on

- car is the variable that holds a racecar object

- The car.move() method takes two ints, the x coordinate and y coordinate of its next location. They make up the point of the upper left hand corner.

OK, so the basic idea is that you can use sine and cosine to convert from an angle to a position on the screen. If r is the radius, then the (x) and (y) coordinates are r * Math.sin(angle) and r * Math.cos(angle), where angle is measured in radians (so goes from 0 to 2 * PI to complete the circle/ellipse), and where you may need to swap round sin/cos depending on whether you start at 12 o'clock or 3 o'clock. And with an ellipse, your radius actually changes as you go round...

So the idea is that each time the car moves, you nudge the angle on by some random amount and then re-calculate the coordinates.

There's actually a problem with this approach: because the radius of the ellipse varies as you go round, the amount of "real distance" covered by a particular change in angle also varies as you go round. So your cars will appear to move faster at the points where the radius is larger.

A couple of ways round this are to (a) either make the maximum "nudge" vary depending on the radius, or (b) each time calculate a DIRECTION based on a fixed increment to the angle, then calculate a random movement in this direction.

commented: Nice post. +21
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.