Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

AI won't move the right way

Discussion in 'Scripting' started by unity_F-Ht0AEJZbf9iA, Aug 6, 2020.

  1. unity_F-Ht0AEJZbf9iA

    unity_F-Ht0AEJZbf9iA

    Joined:
    Jul 29, 2020
    Posts:
    6
    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?

    Code (CSharp):
    1.  
    2. public class Opponent : MonoBehaviour {
    3.  
    4. public GameObject Ball;
    5. public float range;
    6. public float speed;
    7. Rigidbody rb;
    8.  
    9. void Start()
    10. {
    11. rb=GetComponent<Rigidbody>();
    12. }
    13.  
    14. void Update()
    15. {
    16.  
    17. range = Vector3.Distance(Ball.transform.position, transform.position);
    18.  
    19. if (range < 40)
    20. {
    21. transform.LookAt(Ball.transform.position);
    22. }
    23.  
    24. if (range < 30 && range > 15)
    25. {
    26. rb.AddForce(Vector3.forward*25*speed);
    27. }
    28. }
    29. }
    30.  
    This is the code I've been working on, any suggestions on how to fix the problem will be great. Thanks
     
  2. FlipGizmo

    FlipGizmo

    Joined:
    Oct 13, 2018
    Posts:
    13
    I think this line is your problem:
    Code (CSharp):
    1. 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:
    Code (CSharp):
    1. rb.AddForce(transform.forward*25*speed);
     
  3. unity_F-Ht0AEJZbf9iA

    unity_F-Ht0AEJZbf9iA

    Joined:
    Jul 29, 2020
    Posts:
    6
    I've tried that but the AI still moves away from the ball instead of towards it.
     
  4. Giustitia

    Giustitia

    Joined:
    Oct 26, 2015
    Posts:
    113
    Try with

    Code (CSharp):
    1. rb.AddForce((Ball.transform.position - transform.position).normalized*25*speed)
     
  5. FlipGizmo

    FlipGizmo

    Joined:
    Oct 13, 2018
    Posts:
    13
    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.
     
    Giustitia likes this.