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--;
-50,200 => 50,-100
300, 300 => 600,230
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.