Search Unity

AI script

Discussion in 'Scripting' started by oldcollins, Sep 20, 2014.

  1. oldcollins

    oldcollins

    Joined:
    Aug 3, 2012
    Posts:
    111
    Hi there i.m trying to change this script so that it looks for the player and head in its generle direction but using the built in navigaition of unity 3d pro

    so im wondering is anyone can help

    here is the current script

    Code (JavaScript):
    1.  
    2. var speed = 3.0;
    3. var rotationSpeed = 5.0;
    4. var shootRange = 15.0;
    5. var attackRange = 30.0;
    6. var shootAngle = 4.0;
    7. var dontComeCloserRange = 5.0;
    8. var delayShootTime = 0.35;
    9. var pickNextWaypointDistance = 2.0;
    10. var target : Transform;
    11.  
    12. private var lastShot = -10.0;
    13.  
    14. // Make sure there is always a character controller
    15. @script RequireComponent (CharacterController)
    16.  
    17. function Start () {
    18.     // Auto setup player as target through tags
    19.     if (target == null && GameObject.FindWithTag("Player"))
    20.         target = GameObject.FindWithTag("Player").transform;
    21.  
    22.     Patrol();
    23. }
    24.  
    25. function Patrol () {
    26.     var curWayPoint = AutoWayPoint.FindClosest(transform.position);
    27.     while (true) {
    28.         var waypointPosition = curWayPoint.transform.position;
    29.         // Are we close to a waypoint? -> pick the next one!
    30.         if (Vector3.Distance(waypointPosition, transform.position) < pickNextWaypointDistance)
    31.             curWayPoint = PickNextWaypoint (curWayPoint);
    32.  
    33.         // Attack the player and wait until
    34.         // - player is killed
    35.         // - player is out of sight      
    36.         if (CanSeeTarget ())
    37.             yield StartCoroutine("AttackPlayer");
    38.        
    39.         // Move towards our target
    40.         MoveTowards(waypointPosition);
    41.        
    42.         yield;
    43.     }
    44. }
    45.  
    46.  
    47. function CanSeeTarget () : boolean {
    48.     if (Vector3.Distance(transform.position, target.position) > attackRange)
    49.         return false;
    50.        
    51.     var hit : RaycastHit;
    52.     if (Physics.Linecast (transform.position, target.position, hit))
    53.         return hit.transform == target;
    54.  
    55.     return false;
    56. }
    57.  
    58. function Shoot () {
    59.     // Start shoot animation
    60.     animation.CrossFade("shoot", 0.3);
    61.  
    62.     // Wait until half the animation has played
    63.     yield WaitForSeconds(delayShootTime);
    64.    
    65.     // Fire gun
    66.     BroadcastMessage("Fire");
    67.    
    68.     // Wait for the rest of the animation to finish
    69.     yield WaitForSeconds(animation["shoot"].length - delayShootTime);
    70. }
    71.  
    72. function AttackPlayer () {
    73.     var lastVisiblePlayerPosition = target.position;
    74.     while (true) {
    75.         if (CanSeeTarget ()) {
    76.             // Target is dead - stop hunting
    77.             if (target == null)
    78.                 return;
    79.  
    80.             // Target is too far away - give up  
    81.             var distance = Vector3.Distance(transform.position, target.position);
    82.             if (distance > shootRange * 3)
    83.                 return;
    84.            
    85.             lastVisiblePlayerPosition = target.position;
    86.             if (distance > dontComeCloserRange)
    87.                 MoveTowards (lastVisiblePlayerPosition);
    88.             else
    89.                 RotateTowards(lastVisiblePlayerPosition);
    90.  
    91.             var forward = transform.TransformDirection(Vector3.forward);
    92.             var targetDirection = lastVisiblePlayerPosition - transform.position;
    93.             targetDirection.y = 0;
    94.  
    95.             var angle = Vector3.Angle(targetDirection, forward);
    96.  
    97.             // Start shooting if close and play is in sight
    98.             if (distance < shootRange && angle < shootAngle)
    99.                 yield StartCoroutine("Shoot");
    100.         } else {
    101.             yield StartCoroutine("SearchPlayer", lastVisiblePlayerPosition);
    102.             // Player not visible anymore - stop attacking
    103.             if (!CanSeeTarget ())
    104.                 return;
    105.         }
    106.  
    107.         yield;
    108.     }
    109. }
    110.  
    111. function SearchPlayer (position : Vector3) {
    112.     // Run towards the player but after 3 seconds timeout and go back to Patroling
    113.     var timeout = 3.0;
    114.     while (timeout > 0.0) {
    115.         MoveTowards(position);
    116.  
    117.         // We found the player
    118.         if (CanSeeTarget ())
    119.             return;
    120.  
    121.         timeout -= Time.deltaTime;
    122.         yield;
    123.     }
    124. }
    125.  
    126. function RotateTowards (position : Vector3) {
    127.     SendMessage("SetSpeed", 0.0);
    128.    
    129.     var direction = position - transform.position;
    130.     direction.y = 0;
    131.     if (direction.magnitude < 0.1)
    132.         return;
    133.    
    134.     // Rotate towards the target
    135.     transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
    136.     transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
    137. }
    138.  
    139. function MoveTowards (position : Vector3) {
    140.     var direction = position - transform.position;
    141.     direction.y = 0;
    142.     if (direction.magnitude < 0.5) {
    143.         SendMessage("SetSpeed", 0.0);
    144.         return;
    145.     }
    146.    
    147.     // Rotate towards the target
    148.     transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
    149.     transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
    150.  
    151.     // Modify speed so we slow down when we are not facing the target
    152.     var forward = transform.TransformDirection(Vector3.forward);
    153.     var speedModifier = Vector3.Dot(forward, direction.normalized);
    154.     speedModifier = Mathf.Clamp01(speedModifier);
    155.  
    156.     // Move the character
    157.     direction = forward * speed * speedModifier;
    158.     GetComponent (CharacterController).SimpleMove(direction);
    159.    
    160.     SendMessage("SetSpeed", speed * speedModifier, SendMessageOptions.DontRequireReceiver);
    161. }
    162.  
    163. function PickNextWaypoint (currentWaypoint : AutoWayPoint) {
    164.     // We want to find the waypoint where the character has to turn the least
    165.  
    166.     // The direction in which we are walking
    167.     var forward = transform.TransformDirection(Vector3.forward);
    168.  
    169.     // The closer two vectors, the larger the dot product will be.
    170.     var best = currentWaypoint;
    171.     var bestDot = -10.0;
    172.     for (var cur : AutoWayPoint in currentWaypoint.connected) {
    173.         var direction = Vector3.Normalize(cur.transform.position - transform.position);
    174.         var dot = Vector3.Dot(direction, forward);
    175.         if (dot > bestDot && cur != currentWaypoint) {
    176.             bestDot = dot;
    177.             best = cur;
    178.         }
    179.     }
    180.    
    181.     return best;
    182. }
     
  2. oldcollins

    oldcollins

    Joined:
    Aug 3, 2012
    Posts:
    111
    Go a New AI Script but keep Getting this error
    NullReferenceException: Object reference not set to an instance of an object
    Boo.Lang.Runtime.RuntimeServices.InvokeBinaryOperator (System.String operatorName, System.Object lhs, System.Object rhs)
    Enemy_GroundUnit.FixedUpdate () (at Assets/Test Scripts/Enemy_GroundUnit.js:48)
    Code (JavaScript):
    1. //This line should always be present at the top of scripts which use pathfinding
    2. import Pathfinding;
    3.  
    4.  
    5.     var tankTurret : Transform;
    6.     var tankBody : Transform;
    7.     var tankCompass : Transform;
    8.     var turnSpeed : float = 10.0;
    9.  
    10.     var targetPosition : Vector3; //the destination postion
    11.     var seeker : Seeker; //the seeker component on this object, this aids in building my path
    12.     var controller : CharacterController; //the charactor controller component on this object
    13.     var path : Path; //this will hold the path to follow
    14.     var nextWaypointDistance : float = 3.0; //mininum distance required to move toward next waypoint
    15.     private var currentWaypoint : int = 0; //index of the waypoint this object is currently at
    16.  
    17.     //do this right away, of course!
    18.     function Start()
    19.     {
    20.         targetPosition = GameObject.FindWithTag("Player").transform.position;
    21.         GetNewPath();
    22.     }
    23.  
    24.     //this function, when called, will generate a new path from this object to the "targetPosition"
    25.     function GetNewPath()
    26.     {
    27.         //Debug.Log("getting new path!");
    28.         seeker.StartPath(transform.position,targetPosition, OnPathComplete); //tell the seeker component to determine the path
    29.     }
    30.  
    31.     //this function will be called when the seeker has finished determining the path
    32.     function OnPathComplete(newPath : Path) //the newly determined path is sent over as "newPath", type of "Path"
    33.     {
    34.         if (!newPath.error) //if the new path does not have any errors...
    35.         {
    36.             path = newPath; //set the path to this new one
    37.             currentWaypoint = 0; //now that we have a new path, make sure to start at the first waypoint
    38.         }
    39.     }
    40.  
    41.     //this function is called by Unity every physics "frame" (ie, many times per second, much like "function Update()")
    42.     function FixedUpdate()
    43.     {
    44.         if(path == null) //no path?
    45.         {
    46.             return; //...then don't do anything!
    47.         }
    48.         if(currentWaypoint >= path.vectorPath.Length) //reached end of path?
    49.         {
    50.             return; //do...something? We'll do nothing for now...
    51.         }
    52.        
    53.         //find direction to next waypoint
    54.         var dir : Vector3 = (path.vectorPath[currentWaypoint]-transform.position).normalized;
    55.         //find an amount, based on speed, direction, and delta time, to move
    56. //        dir *= forwardSpeed * Time.fixedDeltaTime;
    57.        
    58.         //move! :)
    59.         controller.SimpleMove (dir);
    60.        
    61.         //rotate to face next waypoint
    62.         //transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(path.vectorPath[currentWaypoint]),1);
    63.         tankCompass.LookAt(path.vectorPath[currentWaypoint]);
    64.         tankBody.rotation = Quaternion.Lerp(tankBody.rotation, tankCompass.rotation, Time.deltaTime*turnSpeed);
    65.         //transform.LookAt(path.vectorPath[currentWaypoint]);
    66.        
    67.         //Check if we are close enough to the next waypoint
    68.         if (Vector3.Distance (transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance)
    69.         {
    70.             currentWaypoint++; //If we are, proceed to follow the next waypoint
    71.         }
    72.     }
    73.  
    any Help Would Be great
     
  3. eelstork

    eelstork

    Joined:
    Jun 15, 2014
    Posts:
    221
    Check whether path.vectorpath is null when you get the error?