user1217946
user1217946

Reputation:

Moving directly from Point A to Point B

I got x and y (My position) and also destination.x and destination.y (where I want to get). This is not for homework, just for training.

So what I did already is

float x3 = x - destination.x;
float y3 = y - destination.y;

float angle = (float) Math.atan2(y3, x3);
float distance = (float) Math.hypot(x3, y3);

I got angle and distance but don't know how to make it move directly. Please help! Thanks!

Upvotes: 1

Views: 2543

Answers (3)

Silvano Brugnoni
Silvano Brugnoni

Reputation: 424

I recommend calculating the x and y components of your movement independently. using trigonometric operations slows your program down significantly.

a simple solution for your problem would be:

float dx = targetX - positionX;
float dy = targetY - positionY;

positionX = positionX + dx;
positionY = positionY + dy;

in this code example, you calculate the x and y distance from your position to your target and you move there in one step.

you can apply a time factor (<1) and do the calculation multiple times, to make it look like your object is moving.

Note that + and - are much faster than cos(), sin() etc.

Upvotes: 1

SteveL
SteveL

Reputation: 3389

To calculate the velocity from a given angle use this:

velx=(float)Math.cos((angle)*0.0174532925f)*speed;
vely=(float)Math.sin((angle)*0.0174532925f)*speed;

*speed=your speed :) (play with the number to see what is the right)

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

Maybe using this will help

float vx = destination.x - x;
float vy = destination.y - y;
for (float t = 0.0; t < 1.0; t+= step) {
  float next_point_x = x + vx*t;
  float next_point_y = y + vy*t;
  System.out.println(next_point_x + ", " + next_point_y);
}

Now you have the coordinates of the points on the line. Choose step to small enough according to your need.

Upvotes: 1

Related Questions