John Doe
John Doe

Reputation: 29

Prevent AI Shaking

I have an AI which is a goalkeeper which tries to stop as many balls going in to the goal. There can be more than one ball heading towards the goal. The AI constantly checks (checks once a frame) which ball is the closest and tries to stop the closest ball.

Lets say the goalkeeper is in the middle of the goal and two balls, ball 1 and ball 2, one heading towards the right and the other towards the left of the goal. Both of which are the same distance away from the goal (or both distance are very close) . The goalkeeper starts to shake.

I am guessing this occurs because at one frame ball 1 is closest so it moves towards ball 1 and then the next frame ball 2 is the closest so it moves towards ball 2...then ball 1 then ball 2 then ball 1...etc.

How do I prevent this from happening? If someone wants to provide coding i am using Unity engine and coding in C#.

EDIT 1: Both balls are traveling at the same rate.

EDIT 2: The code I am using to check for the closest ball. This is done every frame.

GameObject FindClosestBall() {
    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("Ball");
    GameObject closest;
    float distance = Mathf.Infinity;
    Vector3 position = transform.position;
    foreach (GameObject go in gos) {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance) {
            closest = go;
            distance = curDistance;
        }
    }
    return closest;
}

Upvotes: 0

Views: 212

Answers (1)

Paul
Paul

Reputation: 141829

You might try setting a threshold that must be met for two distances to be considered unequal.

For example, suppose you pick a threshold of 0.5:

Then if Ball 1 is at a distance of 4.8 and Ball 2 is at a distance of 5.0, you would consider them equal distance and choose between them by a tie-breaking method (ie, pick ball 1 over ball 2, because 1 < 2).

Adjust the threshold until it works well.

Upvotes: 1

Related Questions