開始点と終了点、および距離を指定して、線に沿って点を計算します

StackOverflow https://stackoverflow.com/questions/1800138

質問

直線上にあるポイントを計算する最も簡単な方法を探しています 線の終点から与えられた距離:

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 = ???
}  

回答に感謝します。これは宿題ではありません。 私の通常の専門分野。

これは以下に提案する機能です。仕事に近いわけではありません。もし私が の右上90度部分で5度ごとにポイントを計算する 開始点として円を使用し、円の中心をx2、y2として以下の関数を呼び出します。距離が4の場合、終点はまったく間違っています。それらは中心の右下にあり、長さは中心点と同じ長さです。誰でも提案がありますか?

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) );

}

このソリューションを見つけましたstackoverflowが、それを完全に理解していない、誰でも明確にできますか?

役に立ちましたか?

解決

これはMathOverflowに属していると思いますが、これはあなたの最初の投稿なので答えます。 まず、x1y1からx2y2へのベクトルを計算します:

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

次に長さを計算します:

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

ベクトルを単位長に正規化します:

vx /= mag;
vy /= mag;

最後に、新しいベクトルx2y2 + vxvy *(mag + distance)を計算します。

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

代わりに、距離/ magで乗算する計算の一部を省略できます。

他のヒント

これらの方程式は間違っています:

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

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

正しい方程式は次のとおりです。

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

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

トム

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top