开发者

Given a start and end point, and a distance, calculate a point along a line

Looking for the quickest way to calculate a point that lies on a line a given distance away from the end point of the line:

void calculate_line_point(int x1, int y1, int x2, int y2, int distance, int *px, int *py) 
{
    //calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2
    *px = ???
    *py = ???
}  

Thanks for the responses, no this is开发者_StackOverflow中文版 not homework, just some hacking out of my normal area of expertise.

This is the function suggested below. It's not close to working. If I calculate points every 5 degrees on the upper right 90 degree portion of a circle as starting points and call the function below with the center of the circle as x2,y2 with a distance of 4 the end points are totally wrong. They lie below and to the right of the center and the length is as long as the center point. Anyone have any suggestions?

void calculate_line_point(int x1, int y1, int x2, int y2, int distance)
{

//calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2

  double vx = x2 - x1; // x vector
  double vy = y2 - y1; // y vector

  double mag = sqrt(vx*vx + vy*vy); // length

  vx /= mag;
  vy /= mag;

// calculate the new vector, which is x2y2 + vxvy * (mag + distance).

  px = (int) ( (double) x2 + vx * (mag + (double)distance) );
  py = (int) ( (double) y2 + vy * (mag + (double)distance) );

}

I've found this solution on stackoverflow but don't understand it completely, can anyone clarify?


I think this belongs on MathOverflow, but I'll answer since this is your first post. First you calculate the vector from x1y1 to x2y2:

float vx = x2 - x1;
float vy = y2 - y1;

Then calculate the length:

float mag = sqrt(vx*vx + vy*vy);

Normalize the vector to unit length:

vx /= mag;
vy /= mag;

Finally calculate the new vector, which is x2y2 + vxvy * (mag + distance).

*px = (int)((float)x1 + vx * (mag + distance));
*py = (int)((float)y1 + vy * (mag + distance));

You can omit some of the calculations multiplying with distance / mag instead.


These equations are wrong:

px = (int) ( (double) x2 + vx * (mag + (double)distance) );

py = (int) ( (double) y2 + vy * (mag + (double)distance) );

The correct equations are:

px = (int) ( (double) x2 + vx * (double)distance );

py = (int) ( (double) y2 + vy * (double)distance );

Tom

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜