Search Unity

Look at target for a random wandering ai script C# 5.5 3d

Discussion in 'Scripting' started by Jeremie-de-Vos, Mar 21, 2017.

  1. Jeremie-de-Vos

    Jeremie-de-Vos

    Joined:
    Jun 5, 2015
    Posts:
    120
    Hey,
    I'm struggling a wile whit this one.
    but still i did't figure it out.
    I want the Nav Mesh Agent look at the direction it is walking.
    what can i do to make that happen?!

    All help is appreciated!

    Code:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.AI;
    4.  
    5. public class WanderingAI : MonoBehaviour
    6. {
    7.  
    8.     public float wanderRadius;
    9.     public float wanderTimer;
    10.     public float turnSpeed = 7f;
    11.  
    12.     private Transform target;
    13.     private NavMeshAgent agent;
    14.     private float timer;
    15.  
    16.     void OnEnable()
    17.     {
    18.         agent = GetComponent<NavMeshAgent>();
    19.         timer = wanderTimer;
    20.     }
    21.     void Update()
    22.     {
    23.         timer += Time.deltaTime;
    24.  
    25.         if (timer >= wanderTimer)
    26.         {
    27.             Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
    28.             agent.SetDestination(newPos);
    29.             timer = 0;
    30.         }
    31.     }
    32.  
    33.  
    34.     public Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask)
    35.     {
    36.         Vector3 randDirection = Random.insideUnitSphere * dist;
    37.  
    38.         randDirection += origin;
    39.      
    40.         NavMeshHit navHit;
    41.  
    42.         NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
    43.  
    44.         Vector3 dir = navHit.position - transform.position;
    45.         Quaternion lookRotation = Quaternion.LookRotation(dir);
    46.         Vector3 rotation = Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
    47.         transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);
    48.  
    49.         return navHit.position;
    50.     }
    51. }