Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Simple AI script

Discussion in 'Scripting' started by rmele09, Jun 7, 2015.

  1. rmele09

    rmele09

    Joined:
    Nov 8, 2010
    Posts:
    712
    I am using a script that follows a player and rotates toward the player as well. It is working, but I need help extending this. Right now the enemy character will follow and rotate correctly, however, when the enemy enters the "stop" range, I need it to continue to rotate toward the player. Right now, you can rotate around the enemy while staying in range, which is not good. I need the rotate to always be constant even while in "stopped". Here is the script so far:

    Code (JavaScript):
    1. var target : Transform; //the enemy's target
    2. var moveSpeed = 3; //move speed
    3. var rotationSpeed = 5; //speed of turning
    4. var range : float = 10f;
    5. var range2 : float = 10f;
    6. var stop : float = 3;
    7. var myTransform : Transform; //current transform data of this enemy
    8.  
    9. // rotate to look at the player
    10. var distance = Vector3.Distance(myTransform.position, target.position);
    11. if (distance <= range2 && distance >= range)
    12. {
    13. myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
    14. Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
    15. }
    16.  
    17. // move towards the player
    18. if (distance <= range && distance > stop)
    19. {
    20.  
    21. myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
    22. Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
    23. myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
    24. }
    25. // Stop
    26. if (distance <= stop)
    27. {
    28. myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
    29. Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
     
    Last edited: Jun 8, 2015
  2. rmele09

    rmele09

    Joined:
    Nov 8, 2010
    Posts:
    712
  3. rmele09

    rmele09

    Joined:
    Nov 8, 2010
    Posts:
    712
    Solved this. I simply removed the conditions for the rotate and it works all the time now.
     
  4. malithayesh2002

    malithayesh2002

    Joined:
    Jul 27, 2018
    Posts:
    1
    I need free roaming game civil AI
     
  5. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,754
    Which is not necessary simple AI. Civil as NPS, or Civil as Civilisation?
    Anyway. asset store is one way to go, forum search second, then github and finally other web browser search engines.