Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by MamoruK · May 05, 2014 at 09:31 PM · c#raycast

AI sight script not detecting player

So here's the script I'm working with. I've compared it to numerous others and i can't figure out why it's not working in game. I get no errors but the raycasing seems to not be properly targeting the player. there is also a way point script attached to the enemy as well so i don't know if that is what is causing the issue.

here's the sight script enter code hereusing UnityEngine; using System.Collections;

 public class SightAI : MonoBehaviour
 {
     public float fieldOfViewAngle = 110.0f;                // Number of degrees, centred on forward, for the enemy see.
     public bool playerInSight;                            // Whether or not the player is currently sighted.
     public Vector3 personalLastSighting;                // Last place this enemy spotted the player.
     
     
     private NavMeshAgent nav;                            // Reference to the NavMeshAgent component.
     private SphereCollider col;                            // Reference to the sphere collider trigger component.
     private Animator anim;                                // Reference to the Animator.
     private LastPlayerSighting lastPlayerSighting;    // Reference to last global sighting of the player.
     private GameObject player;                            // Reference to the player.
     private Animator playerAnim;                        // Reference to the player's animator component.
     private HashIDs hash;                            // Reference to the HashIDs.
     private Vector3 previousSighting;                    // Where the player was sighted last frame.
     
     
     void Awake ()
     {
         // Setting up the references.
         nav = GetComponent<NavMeshAgent>();
         col = GetComponent<SphereCollider>();
         anim = GetComponent<Animator>();
         lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<LastPlayerSighting>();
         player = GameObject.FindGameObjectWithTag(Tags.player);
         playerAnim = player.GetComponent<Animator>();
         hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<HashIDs>();
         
         // Set the personal sighting and the previous sighting to the reset position.
         personalLastSighting = lastPlayerSighting.resetPosition;
         previousSighting = lastPlayerSighting.resetPosition;
     }
     
     
     void Update ()
     {
         // If the last global sighting of the player has changed...
         if(lastPlayerSighting.position != previousSighting)
             // ... then update the personal sighting to be the same as the global sighting.
             personalLastSighting = lastPlayerSighting.position;
         
         // Set the previous sighting to the be the sighting from this frame.
         previousSighting = lastPlayerSighting.position;
         
 /*        // If the player is alive...
         if(playerHealth.health > 0f)
             // ... set the animator parameter to whether the player is in sight or not.
             anim.SetBool(hash.playerInSightBool, playerInSight);
         else
             // ... set the animator parameter to false.
             anim.SetBool(hash.playerInSightBool, false);
 */
     }
     
     
     void OnTriggerStay (Collider other)
     {
         // If the player has entered the trigger sphere...
         if(other.gameObject == player)
         {
             playerInSight = true;
             // Create a vector from the enemy to the player and store the angle between it and forward.
             Vector3 direction = other.transform.position - transform.position;
             float angle = Vector3.Angle(direction, transform.forward);
 
             Debug.DrawRay(transform.position + transform.up / 2, direction, Color.green);
             // If the angle between forward and where the player is, is less than half the angle of view...
             if(angle < fieldOfViewAngle)
             {
                 RaycastHit hit;
                 
                 // ... and if a raycast towards the player hits something...
                 if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, col.radius))
                 {
                     // ... and if the raycast hits the player...
                     if(hit.collider.gameObject == player)
                     {
                         // ... the player is in sight.
                         playerInSight = true;
                         
                         // Set the last global sighting is the players current position.
                         lastPlayerSighting.position = player.transform.position;
                     }
                 }
             }
         }
             
         // Store the name hashes of the current states.
         int playerLayerZeroStateHash = playerAnim.GetCurrentAnimatorStateInfo(0).nameHash;
         int playerLayerOneStateHash = playerAnim.GetCurrentAnimatorStateInfo(1).nameHash;
             
         //If the player is running or is attracting attention...
         if(playerLayerZeroStateHash == hash.locomotionState || playerLayerOneStateHash == hash.shoutState)
         {
         // ... and if the player is within hearing range...
         if(CalculatePathLength(player.transform.position) <= col.radius)
             {
                 // ... set the last personal sighting of the player to the player's current position.
                 personalLastSighting = player.transform.position;
             }
         }
     }    
     
     void OnTriggerExit (Collider other)
     {
         // If the player leaves the trigger zone...
         if(other.gameObject == player)
             // ... the player is not in sight.
             playerInSight = false;
     }
     
     
     float CalculatePathLength (Vector3 targetPosition)
     {
         // Create a path and set it based on a target position.
         NavMeshPath path = new NavMeshPath();
         if(nav.enabled)
             nav.CalculatePath(targetPosition, path);
         
         // Create an array of points which is the length of the number of corners in the path + 2.
         Vector3 [] allWayPoints = new Vector3[path.corners.Length + 2];
         
         // The first point is the enemy's position.
         allWayPoints[0] = transform.position;
         
         // The last point is the target position.
         allWayPoints[allWayPoints.Length - 1] = targetPosition;
         
         // The points inbetween are the corners of the path.
         for(int i = 0; i < path.corners.Length; i++)
         {
             allWayPoints[i + 1] = path.corners[i];
         }
         
         // Create a float to store the path length that is by default 0.
         float pathLength = 0f;
         
         // Increment the path length by an amount equal to the distance between each waypoint and the next.
         for(int i = 0; i < allWayPoints.Length - 1; i++)
         {
             pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]);
         }
         
         return pathLength;
     }
 }
 

here's the waypoint script

 using UnityEngine;
 using System.Collections;
 
 public class MovementAI_Bob : MonoBehaviour
 {
     public float patrolSpeed = 2f;                            // The nav mesh agent's speed when patrolling.
     public float chaseSpeed = 5f;                            // The nav mesh agent's speed when chasing.
     public float chaseWaitTime = 5f;                        // The amount of time to wait when the last sighting is reached.
     public float patrolWaitTime = 1f;                        // The amount of time to wait when the patrol way point is reached.
     public Transform[] patrolWayPoints;                        // An array of transforms for the patrol route.
     public float timer = 0f;
     public float wayPointNum = 1f;
 
     private SightAI enemySight;                        // Reference to the EnemySight script.
     private NavMeshAgent nav;                                // Reference to the nav mesh agent.
     private Transform player;                                // Reference to the player's transform.
     private LastPlayerSighting lastPlayerSighting;        // Reference to the last global sighting of the player.
     private float chaseTimer;                                // A timer for the chaseWaitTime.
     private float patrolTimer;                                // A timer for the patrolWaitTime.
     private int wayPointIndex;                                // A counter for the way point array.
     private int rotateTimer;
 
     private void RotateCounterClockWise()
     {
         transform.Rotate (Vector3.down * Time.deltaTime * 30);
     }
     
     void Awake ()
     {
         // Setting up the references.
         enemySight = GetComponent<SightAI>();
         nav = GetComponent<NavMeshAgent>();
         player = GameObject.FindGameObjectWithTag(Tags.player).transform;
         lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<LastPlayerSighting>();
     }
     
     
     void Update ()
     {
         // If the player is in sight and is alive...
         wayPointNum = wayPointIndex;
         if (wayPointIndex == 0) 
         {
             rotateTimer = 0;
             timer = 0;
         }
         if (wayPointIndex == 2 || wayPointIndex == 16)
         {
             nav.Stop();
             rotateTimer = 0;
             rotateTimer++;
             timer++;
             if (timer <= 600)
                 RotateCounterClockWise();
             else
             {
                 Patrolling();
             }
         }
         // If the player has been sighted and isn't dead...
         if(enemySight.personalLastSighting != lastPlayerSighting.resetPosition)
             // ... chase.
             Chasing();
         
         // Otherwise...
         else
             // ... patrol.
             Patrolling();
 
     }
     
     
 //    void Shooting ()
 //    {
 //        // Stop the enemy where it is.
 //        nav.Stop();
 //    }
     
     
     void Chasing ()
     {
         // Create a vector from the enemy to the last sighting of the player.
         Vector3 sightingDeltaPos = enemySight.personalLastSighting - transform.position;
         
         // If the the last personal sighting of the player is not close...
         if(sightingDeltaPos.sqrMagnitude > 4f)
             // ... set the destination for the NavMeshAgent to the last personal sighting of the player.
             nav.destination = enemySight.personalLastSighting;
         
         // Set the appropriate speed for the NavMeshAgent.
         nav.speed = chaseSpeed;
         
         // If near the last personal sighting...
         if(nav.remainingDistance < nav.stoppingDistance)
         {
             // ... increment the timer.
             chaseTimer += Time.deltaTime;
             
             // If the timer exceeds the wait time...
             if(chaseTimer >= chaseWaitTime)
             {
                 // ... reset last global sighting, the last personal sighting and the timer.
                 lastPlayerSighting.position = lastPlayerSighting.resetPosition;
                 enemySight.personalLastSighting = lastPlayerSighting.resetPosition;
                 chaseTimer = 0f;
             }
         }
         else
             // If not near the last sighting personal sighting of the player, reset the timer.
             chaseTimer = 0f;
     }
     
     
     void Patrolling ()
     {
         // Set an appropriate speed for the NavMeshAgent.
         nav.speed = patrolSpeed;
         
         // If near the next waypoint or there is no destination...
         if(nav.destination == lastPlayerSighting.resetPosition || nav.remainingDistance < nav.stoppingDistance)
         {
             // ... increment the timer.
             patrolTimer += Time.deltaTime;
             
             // If the timer exceeds the wait time...
             if(patrolTimer >= patrolWaitTime)
             {
                 // ... increment the wayPointIndex.
                 if(wayPointIndex == patrolWayPoints.Length - 1)
                     wayPointIndex = 0;
                 else
                     wayPointIndex++;
                 
                 // Reset the timer.
                 patrolTimer = 0;
             }
         }
         else
             // If not near a destination, reset the timer.
             patrolTimer = 0;
         
         // Set the destination to the patrolWayPoint.
         nav.destination = patrolWayPoints[wayPointIndex].position;
     }
 }
 
 
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Raycasting To Objects 1 Answer

C# More Accurate or Larger Raycast 1 Answer

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

C# Raycast isn't working? 1 Answer

Finding Distance between Angles and Points 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges