Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by Warcraft897 · Sep 25, 2019 at 11:29 AM · ainavmesh

How do I add a chase player if seen for 10 seconds if not in sight while still returning to navmesh patrol route if player is not seen

I am trying to create a script so that in the maze the enemy will go To different points but will chase the player when the enemy can see the player I do not know if I need a camera or not but I know that After 10 seconds of not seeing the player after just seeing him for example the player turns a corner the ai should chase the player for 10 seconds if not seen again within that time return to patrol pattern but I do not know how to make this work any help would be appreciated please help.

p.s just a beginner.

oh yeah here is the script it would be beneficial if you left a copy with the changes in the script in it I am bad with implementing code just from description's thanks.

 using UnityEngine;
     using UnityEngine.AI;
     using System.Collections;
 
 
     public class Patrol : MonoBehaviour {
 
         public Transform[] points;
         private int destPoint = 0;
         private NavMeshAgent agent;
 
         public GameObject Player;
 
 
         void Start () {
             agent = GetComponent<NavMeshAgent>();
 
             // Disabling auto-braking allows for continuous movement
             // between points (ie, the agent doesn't slow down as it
             // approaches a destination point).
             agent.autoBraking = false;
 
             GotoNextPoint();
         }
 
 
         void GotoNextPoint() {
             // Returns if no points have been set up
             if (points.Length == 0)
                 return;
 
             // Set the agent to go to the currently selected destination.
             agent.destination = points[destPoint].position;
 
             // Choose the next point in the array as the destination,
             // cycling to the start if necessary.
             destPoint = (destPoint + 1) % points.Length;
         }
 
 
         void Update () {
             // Choose the next destination point when the agent gets
             // close to the current one.
             if (!agent.pathPending && agent.remainingDistance < 0.5f)
                 GotoNextPoint();
         }
 
         }

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

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Warcraft897 · Sep 26, 2019 at 02:34 PM

@derpypickachu01 thanks I will try to make it work though it is not working now I will see what I can do thanks I will update you today later on what happened thank you

Comment
Add comment · Show 3 · Share
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
avatar image supa4plex2 · Sep 26, 2019 at 10:54 PM 0
Share

No problem! If you wish, you can tell me what issues you've run in and if you're still experiencing them. I'd be happy to help on your call!

avatar image Warcraft897 supa4plex2 · Sep 27, 2019 at 12:36 AM 0
Share

the enemy is not moving at all for some reason I hit play and he just stands still

avatar image Warcraft897 Warcraft897 · Sep 27, 2019 at 12:39 AM 0
Share

ok so If I move the enemy transform while in play he moves but when the ray hits the player the ai does not care for some reason

avatar image
0

Answer by supa4plex2 · Sep 26, 2019 at 05:42 AM

I had some difficulty trying to understand what you were getting at here, but I believe I've come up with a solution to what you're asking to do here. I've added and changed a lot of things to fit the function, and I do admit that it may be a bit messy and rushed.


List of changes:

  • Casted a Ray in front of the enemy (this should be visible in the Scene view if Gizmos are turned on) and the ray has a adjustable range to it, meaning it can see for as far as you want it to. The colour of the ray is drawn to be cyan as well.

  • Made a boolean variable which turns true if it's chasing the Player, and false if it's not. If it's true, it will ignore its normal patrolling procedure and only focus on chasing the player.

  • Added a timer of 10 seconds. The timer will countdown if it's chasing the player as soon as the player is out of the enemy's vision. Once the timer hits 0, the enemy will stop chasing the player and resume to its normal patrol.

  • If the enemy is chasing the player it will attempt to go inside of it. Of course, this wouldn't be a problem as the colliders would prevent them both from going inside each other, but this function can be useful to use a OnCollisionEnter() method which would do something as soon as the both of them collide.


Note: I have NOT worked in 3D Environments and I have NOT tested this code out yet. I've worked on my own things in different environments. However, this doesn't completely mean that this code will not work right off the bat, although there is a possibility it might. I've implemented what I already know and what I've learnt in the time I researched to tackle this problem, so I have some confidence in this.

I'm aware that not testing this is deemed as sloppy, but instead I just imagined an environment similar to what you described and imagined scenarios where each line of code I wrote would work in the scene.


I noticed you have a Transform Array for the transforms of the wall gameobjects, I think it may be useful to add all the children wall gameobjects, if you have a parent for them, in script using a for loop.

Needless to say, this script may or may not create errors but it's a basic idea of what's supposed to happen. If you do find any errors, I believe that you can figure it out or get a better answer than this. Wish you the best of luck on your project!


The Changed Script

 using UnityEngine;
 using UnityEngine.AI;
 using System.Collections;
 using System.Collections.Generic;
 
 
 public class Patrol : MonoBehaviour
 {
 
     public Transform[] points;
     private int destPoint = 0;
     private NavMeshAgent agent;
 
     public float rayDistance = 5f;
     private float timeToChase;
     private bool isChasingPlayer;
     public LayerMask whatToDetect;
     public Transform playerTransform;
 
 
     void Start()
     {
         agent = GetComponent<NavMeshAgent>();
 
         // Disabling auto-braking allows for continuous movement
         // between points (ie, the agent doesn't slow down as it
         // approaches a destination point).
         agent.autoBraking = false;
         timeToChase = 10f;
         isChasingPlayer = false;
 
         if (playerTransform == null)
             Debug.Log("Error. Can't find Player Transform.");
         else
             playerTransform = GameObject.Find("Player").transform;
 
         CheckAndChase();
     }
 
     void CheckAndChase()
     {
         // Returns if no points have been set up
         if (points.Length == 0)
             return;
 
         RaycastHit hitInfo;
         if (Physics.Raycast(transform.position, transform.forward, out hitInfo, rayDistance, whatToDetect))
         {
             if (hitInfo.collider != null)
             {
                 // If the ray detects a collider of a GameObject with the tag "Player"
                 if (hitInfo.collider.CompareTag("Player"))
                 {
                     isChasingPlayer = true;
 
                     // Each time it detects the Player, the timer is reset to 10 seconds. As soon as the Player is out of the
                     //  Enemy's range, the timer begins to count down.
                     timeToChase = 10f;
                 }
                 // If the Player isn't being detected anymore, the enemy will still change the Player.
                 else if (isChasingPlayer == true)
                 {
                     if (timeToChase > 0)
                     {
                         agent.destination = playerTransform.position;
                         timeToChase -= Time.deltaTime;
                     }
                     else
                         isChasingPlayer = false;
                 }
 
                 else
                 {
                         // Set the agent to go to the currently selected destination.
                         agent.destination = points[destPoint].position;
 
                         // Choose the next point in the array as the destination,
                         // cycling to the start if necessary.
                         destPoint = (destPoint + 1) % points.Length;
                 }
             }
         }
     }
 
     void OnDrawGizmosSelected()
     {
         Debug.DrawLine(transform.position, transform.forward * rayDistance, Color.cyan);
     }
 
 
     void Update()
     {
         // Choose the next destination point when the agent gets
         // close to the current one.
         if (!agent.pathPending && ((agent.remainingDistance < 0.5f && isChasingPlayer == false) || isChasingPlayer == true))
             CheckAndChase();
     }
 
 }


Comment
Add comment · Show 1 · Share
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
avatar image supa4plex2 · Sep 26, 2019 at 01:28 PM 0
Share

I forgot to add this important step:

For the whatToDetect Layer$$anonymous$$ask, you need to assign the layers in which the enemy is situated in and the other layer in which the walls are situated in. You can achieve this in the Inspector as I've made that Layer$$anonymous$$ask public.

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

186 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 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 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 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 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 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 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 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 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

Can you use NavMesh agents to vary driving/handling model? 0 Answers

NavMesh Agent Obstacle Avoidance Ignore 1 Answer

How to add variables to Components (Nav Mesh Agent)? 0 Answers

Modify NavMeshPath for Tactical FPS (slicing the pie/sweeping maneuver) 0 Answers

Navmesh baking -- Odd results 1 Answer


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