2017-12-27 35 views
0

オブジェクトとターゲットがあります。彼らはどちらも時間の経過とともに変化するXとZの位置を持っています。C#XNAオブジェクトがX軸とZ軸のターゲットに移動しているかどうかを確認する方法

私は現在の位置と前の位置を追跡します。 ポジションは正または負にすることができます。

現在、オブジェクトが指定されたターゲットに向かって移動しているかどうかを確認する方法を見つけようとしています。

これは私が私の提案はこのように、「この」の間の距離とターゲットを比較することです

if ((Math.Abs(this.previousPosition.X) - Math.Abs(this.currentPosition.X)) > Math.Abs(target.currentPosition.X) 
     && (Math.Abs(this.previousPosition.Z) - Math.Abs(this.currentPosition.Z)) > Math.Abs(target.currentPosition.Z)) 
    { 
     //is moving to target 
     return true; 
    } 
     //is not moving to target 
     return false; 
+1

基本的に(this.previousPosition - this.currentPosition).Magnitude

+0

@AluanHaddad私は大きさがないVector3を使用していますが、同じ長さですか? –

+1

はい、実際にはあなたが望むものを正確に実行する 'Vector3.Distance'静的メンバーがあります。 –

答えて

0

に取り組んでいますコードです:私が代わりにVector3.DistanceSquaredを使用

private bool IsApproachingTarget(double epsilon) 
{ 
    float prevDist, currDist; 
    Vector3.DistanceSquared(ref this.previousPosition, ref target.previousPosition, out prevDist); 
    Vector3.DistanceSquared(ref this.currentPosition, ref target.currentPosition, out currDist); 
    return IsLess(currDist, prevDist, epsilon); 
} 


[MethodImpl(MethodImplOptions.AggressiveInlining)] 
/// <summary> 
/// Robust implementation of a &lt; b, handling floating point imprecisions 
/// </summary> 
public bool IsLess(double a, double b, double epsilon) 
{ 
    return a < b - epsilon; 
} 

注意Vector3.Distanceのベクトルの大きさを比較したいだけで、実際の大きさには興味がないので、このような不要な平方根計算をスキップするのが一般的なパフォーマンスの仕組みです。

Morever、多分簡単なManhattan distanceは同様にあなたのためだろう、この方法は、距離の計算が二回行われているので、あなたは...、各ゲームループに

を結果を保存することができそしてVector3.DistanceSquaredはEuclidean distanceを測定します。

MethodImpl属性は、.NET 4.5で導入された特別な最適化機能です。以前の.NET Frameworkのバージョンをターゲットにしている場合は、スキップすることができます。

関連する問題