This week's book giveaway is in the Android forum. We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line! See this thread for details.

This doesn't have much to do with the Java language specifically, but is a math problem encountered in the coding of my Java simulation.

So I am working on a simulation that allows you to set a vector of waypoints for a tank, which then drives to each of the points.

As of right now, it is all text based. Both the tank and a waypoint have two double coordinates: one for X and one for Y.

The tank starts at 0,0. The waypoint is defined by the user. Say the waypoint is (100,100). I would the tank to step incrementally towards the waypoint goal, in a straight line. Each step would add to the tank's location X and Y.

The hard part is that I want this step to be a constant distance no matter how long the line from (0,0) to (waypointX, waypointY) is. I can do this as long as the slope is less than 1 with the following equations:
tankX = tankX + (CONSTANT_DISTANCE * (1 - (waypointY/waypointX) ) );
tankY = tankY + (CONSTANT_DISTANCE * (waypointY/waypointX) );

waypointY/waypointX is the slope of the line going towards the waypoint. But, if the slope >= 1, the equation no longer works properly.

The question: does anyone know of ONE equation that would increment the tank towards the waypoint regardless of whether slope is less than, equal to, or greater than one?

I'll keep scribbling in my notebooks and let you know if I get something, but if someone has encountered this problem before, that would be great.

John Danek
Greenhorn

Joined: Jun 12, 2009
Posts: 25

posted

0

I should have waited another 10 minutes to run to the forums haha.

The correct way to get the distance per X and Y is:

I think this is principally the same as finding the cosine, but I'm not sure. Anyways, it works for all slopes.

I don't know about cosines, but keep in mind that when you have two points(x1,y1) and (x2,y2) in two dimensional space, then you have a straight line. So

the slope is (y2-y1)/(x2-x1) and that slope is constant, as long as the start point and the destination point don't change. And since it's a constant slope, then the same change in the x co-ordinate each will produce the same distance travelled each time.

Anyways, it's probably just another way of expressing what you already have.