简体   繁体   中英

C# XNA How to tell if object is moving to target on X and Z Axis

So I have an Object and a target. They both have X and Z positions that change over time.

I keep track of there current position and previous position. The positions can be positive or negative.

I am currently trying to figure out a method to tell if an object is moving towards the specified target.

This is the code I am working on

    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;

My suggestion is to compare the distance between 'this' and the target, like this:

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

Note that I used Vector3.DistanceSquared instead of Vector3.Distance. It's a common performance trick, that if you only want to compare the magnitude of vectors and you are not interested in the actual magnitude to skip an unnecessary square root calculation like this.

Morever, you can store the result in each game loop, because this way the distance calculations are made twice...

And Vector3.DistanceSquared measures Euclidean distance , maybe a simple Manhattan distance would do for you as well.

The MethodImpl attribute is just an extra optimization feature introduced in .NET 4.5. You can skip it if you target earlier .NET Framework versions.

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