简体   繁体   中英

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!

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM