File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Game Development and the fly likes Need math/trig(?) help for Java game Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Game Development
Bookmark "Need math/trig(?) help for Java game" Watch "Need math/trig(?) help for Java game" New topic

Need math/trig(?) help for Java game

John Danek

Joined: Jun 12, 2009
Posts: 25
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

Joined: Jun 12, 2009
Posts: 25
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.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 684
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.
It is sorta covered in the JavaRanch Style Guide.
subject: Need math/trig(?) help for Java game
It's not a secret anymore!