Polarbear0106 - 4 months ago 17

Java Question

I need help making an algorithm for moving an object defined by x/y coordinates to another, but it should move in a straight line. I tried something similar a while back, but it moved until it was aligned with the axis. That code looked like this:

`if(x < otherObject.x) x++;`

else if(x > otherObject.x) x--;

if(y < otherObject.y) y++;

else if(y > otherObject.y) y--;

This is a highly inefficient system, and I have been looking at other ways to go about this.

But I also have to move at a specific speed which is what I have been struggling to solve. Example of coordinate movement:

`-50,200 => 50,-100`

300, 300 => 600,230

Any ideas?

The goal is to get it to move in a straight line from point A to B, but it should move at an even speed. Considering this:

The goal is to get it to move through the line, and the speed should make it stay on the line(some inaccuracy is acceptable, but it aligning to the X/Y axis(meaning targetX/targetY is equal to currentX/currentY should not happen).

Answer

First of all, you need to forget the concept of movement from a given "source" point to a given "target" point.

Instead, think of your object at any given moment as being at a **current** point, and moving in a certain **direction** with a certain **speed**.

You will need a real number to hold the angle (in radians) representing the direction your object is moving. If your object needs to go from source position (sx,sy) to target position (tx,ty) then the angle is computed as follows:

```
float deltaX = tx - sx;
float deltaY = ty - sy;
float angle = Math.atan2( deltaY, deltaX );
```

You will also need a real number to hold the speed at which your object is traveling. Ideally your speed should be expressed in terms of screen units (pixels?) per second, but let's keep things simple and just let speed be expressed in terms of screen units per frame. "Frame" simply means "whenever you get around to calculating stuff and rendering stuff". You may be doing this as fast as you can, or you may be doing it 30 times per second, the choice is yours.

So, given all of the above parameters, to calculate your object's new position at each frame, use the following:

```
currentX += speed * Math.cos( angle );
currentY += speed * Math.sin( angle );
```

To find out whether your object has reached the "target" point, compute the distance between your object and the "target" point, and if it is small enough, consider it "there". Do not expect the current point of your object to ever become equal to the target point, that would require too much precision.