AI won't move the right way

I’ve been working on this Proximity AI script for a few weeks now, I have been tweaking and improving by asking for help and finally the script has no compiler errors and works without any issues. However the AI object I assigned the script to, doesn’t move forward towards the ball but instead moves away from it as the ball gets near it. What can I do to fix this?

public class Opponent : MonoBehaviour {

public GameObject Ball;
public float range;
public float speed;
Rigidbody rb;

void Start()
{
rb=GetComponent<Rigidbody>();
}

void Update()
{

range = Vector3.Distance(Ball.transform.position, transform.position);

if (range < 40)
{
transform.LookAt(Ball.transform.position);
}

if (range < 30 && range > 15)
{
rb.AddForce(Vector3.forward*25*speed);
}
}
}

This is the code I’ve been working on, any suggestions on how to fix the problem will be great. Thanks

I think this line is your problem:

rb.AddForce(Vector3.forward*25*speed);

You’re moving your AI in the world’s forward direction which won’t change. You want your AI’s local forward which will change as it rotates.

Try this instead:

rb.AddForce(transform.forward*25*speed);

I’ve tried that but the AI still moves away from the ball instead of towards it.

Try with

rb.AddForce((Ball.transform.position - transform.position).normalized*25*speed)

Guistitia’s answer should work, but also make sure that the blue z-axis is pointing in the forward direction on your AI game object. It sounds like it’s probably pointing behind your AI.

1 Like