2D AI Follow Better

I’m creating a Sports game with my friend and i have ran into a problem, i have tried to make an ai that follows the ball on the x axis only for now but there is a glitch where when it gets near the ball the ai starts to glitch out by moving back and forward from the ball and its really annoying, hope you can help.
public class OpponentAi : MonoBehaviour {

	public float oppSpeed;

	Rigidbody2D oppRB;

	GameObject ball;


	public GameObject opp;


	// Use this for initialization
	void Start () {
		oppRB = GetComponent<Rigidbody2D> ();

		opp = GetComponent<GameObject> ();
	}
	
	// Update is called once per frame
	void Update () {

		ball = GameObject.FindGameObjectWithTag ("Ball");

		if (opp.transform.position.x >= ball.transform.position.x) {
			oppRB.velocity = new Vector2 (-oppSpeed, oppRB.velocity.y);
		}
		if (opp.transform.position.x <= ball.transform.position.x) {
			oppRB.velocity = new Vector2 (oppSpeed, oppRB.velocity.y);
		}

	}
}

Hi there,

Your problem is right here:

 // Update is called once per frame
 void Update () {
 
     ball = GameObject.FindGameObjectWithTag ("Ball");
 
     if (opp.transform.position.x >= ball.transform.position.x) {
         oppRB.velocity = new Vector2 (-oppSpeed, oppRB.velocity.y);
     }
     if (opp.transform.position.x <= ball.transform.position.x) {
         oppRB.velocity = new Vector2 (oppSpeed, oppRB.velocity.y);
     }

}

To begin with I’d cache the ball in the Start function as performing it with every Update cycle isn’t particularly efficient.

The main issue is that you have no condition for when your AI has reached the ball. At the minute, the code is essentially saying :

if (AI has ran past the ball)
{
     Run back towards it;
}

if (AI has not yet reached the ball)
{
     Run towards it.
}

This is what is causing your AI to “glitch out”.

A simple distance check from your player to the ball in Update would allow you to implement the behaviour you would like when your AI is near the ball.

Example:

float distance = 1f;

void Start() {

     ball = GameObject.FindGameObjectWithTag ("Ball");
}

void Update () {

if (opp.transform.position.x - ball.transform.position.x <= distance)
{
     DoWhatYouNeedHere
}

}

You could then stop the AI, make him jump or do whatever it is you need to do when he gets near the ball.