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 /
This question was closed Mar 04, 2020 at 07:16 PM by SSpecks for the following reason:

Other

avatar image
0
Question by SSpecks · Mar 02, 2020 at 06:41 PM · follownpcfollow playeragentfollow path

Make an NPC follow player?

alt textThank you @lightmaster905 for getting me this far, but i still have questions. I am trying to make my NPC follow a player when it is in the range of the box collider. I added agents, but they dont seem to do anything. The code below is for both the random walking and the seeing player, (until seen comments mean its for the seeing player). thank you so much for your help. using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.AI; using UnityEngine.UIElements;

 public class Walking : MonoBehaviour {
     private float latestDirectionChangeTime;
     private readonly float directionChangeTime = 3f;
     private float characterVelocity = 2f; //Random.Range(.5f, 3f);
     private Vector3 movementDirection;
     private Vector3 movementPerSecond;
     public GameObject alien;
     
     //for the until seen 
     private GameObject player;
     private Transform target;
     private float distance;
     public float sight;
     private NavMeshAgent agent;
  
     
     void Start(){
         latestDirectionChangeTime = 0f;
         calcuateNewMovementVector();
         //for the until seen
         player = GameObject.FindGameObjectWithTag("Player");
         target = player.GetComponent<Transform>();
         agent = GetComponent<NavMeshAgent>();
     }
  
     void calcuateNewMovementVector(){
         //create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
         movementDirection = new Vector3(Random.Range(-1.0f, 1.0f), 0,Random.Range(-1.0f, 1.0f)).normalized;
         movementPerSecond = movementDirection * characterVelocity;
     }
  
     void Update(){
         //if the changeTime was reached, calculate a new movement vector
         if (Time.time - latestDirectionChangeTime > directionChangeTime)
         {
             latestDirectionChangeTime = Time.time;
             calcuateNewMovementVector();
         }
      
         //move enemy: 
         transform.position = new Vector3(transform.position.x + (movementPerSecond.x * Time.deltaTime), 22.45f,
             transform.position.z + (movementPerSecond.z * Time.deltaTime));
         
         //wait a set amount of timeeeeeee
         //if his movement is to the west, then he turns 90 in the y axis
         
         alien.transform.rotation = Quaternion.Slerp (alien.transform.rotation, 
             Quaternion.LookRotation (movementDirection), Time.deltaTime * 4f);
         
         distance = Vector3.Distance(target.position, alien.transform.position);
  
         while (distance <= sight)
         {
             //alien.agent.SetDestination(target.position);
             agent.SetDestination(target.position);
         }
 
        
         // Update is called once per frame
         void UntilSeen()
         {
             /*
              * When the player is 'seen' (goes into the range of the box collider on the NPC)
              * The NPC will follow the player at 2x speed
              *
              * If the player gets out of the NPC's box collider for 10 seconds,
              * the NPC will slow down and go back to the Walking Script
              *
              * i know i need to use waituntil code
              */
         }
     }
 
  
     }
 
   
     
 
 
 
 
 
 


screenshot-9.png (141.7 kB)
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

1 Reply

  • Sort: 
avatar image
1
Best Answer

Answer by spencerz · Mar 02, 2020 at 07:44 PM

Here, get rid of the current script you have on your alien and put this on your alien.also Add a nav agent component to your alien and make sure you bake the ground walkable under the navigation window.

uncomment the animation code if you want to add your animations!

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 
 public enum EnemyState
 {
     PATROL,
     CHASE
 }
   public class EnemyController MonoBehaviour       
 {
      public float walk_Speed = 0.5f;
      public float run_Speed = 4f; 
      public float chase_Distance = 7f;
      private float current_Chase_Distance;    
      public float patrol_Radius_Min = 20f, patrol_Radius_Max = 60f;
      public float patrol_For_This_Time = 15f;
      private float patrol_Timer;
      public NavMeshAgent navAgent;
      private EnemyState enemy_State;
   //   private Animator enemy_Anim;
 
     void Start()
   {
         // enemy_Anim = GetComponent<EnemyAnimations>();
          enemy_State = EnemyState.PATROL;
          navAgent = GetComponent<NavMeshAgent>();
          target= GameObject.FindGameObjectWithTag("Player").transform;
      }
   void Update()
     {
         if (enemy_State == EnemyState.PATROL)
         {
             Patrol();
         }
         if (enemy_State == EnemyState.CHASE)
         {
             Chase();
         }    
     } 
 void Patrol()
     {
         navAgent.isStopped = false;
         navAgent.speed = walk_Speed; 
         patrol_Timer += Time.deltaTime;
         if (patrol_Timer > patrol_For_This_Time)
         {
             SetNewRandomDestination();
             patrol_Timer = 0f;
         }   
         if (navAgent.velocity.sqrMagnitude > 0)
         {
            //set up an animation parameter boolean called isWalking in animation state 
         //machine
        // enemy_Anim.SetBool("isWalking", true);          
         }
         else
         {
          //   enemy_Anim.SetBool("isWalking", false);
         }    
         // find distance between the player and the enemy
         if (Vector3.Distance(transform.position, target.position) <= chase_Distance)
         {
            // enemy_Anim.SetBool("isWalking", false);   
             enemy_State = EnemyState.CHASE;
         }
 void Chase ()
 {
         navAgent.isStopped = false;
         navAgent.speed = run_Speed;
         navAgent.SetDestination(target.position);
         if (navAgent.velocity.sqrMagnitude > 0)
         {
           //  enemy_Anim.SetBool("isRunning", true);
         }
         else
         {
          //  enemy_Anim.SetBool("isRunning", false);
         }
             if (chase_Distance != current_Chase_Distance)
             {
                 chase_Distance = current_Chase_Distance;
             }
         }
         else if (Vector3.Distance(transform.position, target.position) > chase_Distance)
         {
                // player run away from enemy              
              //  enemy_Anim.Run(false);
             enemy_State = EnemyState.PATROL;
             patrol_Timer = patrol_For_This_Time;
             // reset the chase distance to previous
             if (chase_Distance != current_Chase_Distance)
             {
                 chase_Distance = current_Chase_Distance;
             }
         }    
 }    
     void SetNewRandomDestination()
     {  
         float rand_Radius = Random.Range(patrol_Radius_Min, patrol_Radius_Max);
         Vector3 randDir = Random.insideUnitSphere * rand_Radius;
         randDir += transform.position;
         NavMeshHit navHit;    
         NavMesh.SamplePosition(randDir, out navHit, rand_Radius, -1);
         navAgent.SetDestination(navHit.position); 
     }
     public EnemyState Enemy_State
     {
         get; set;
     }
 }
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 SSpecks · Mar 02, 2020 at 08:09 PM 0
Share

should i add this to its own individual script?

avatar image spencerz SSpecks · Mar 02, 2020 at 09:30 PM 0
Share

i updated the code. call it EnemyController and get rid of the walking script

avatar image logicandchaos · Mar 02, 2020 at 08:24 PM 2
Share

ins$$anonymous$$d of using 2 bools like that you should set it up as a FS$$anonymous$$ public enum EnemyState { IDLE, WAL$$anonymous$$ING, CHASING } public EnemyState state;

This avoids all possibilities of isWalking=isChasing. Alternatively you could set up a state machine with bool, in a list and when change states in a function.

 List<bool> states=new List<bool>();
 public void SetState(int p_state)
 {
 if(p_state>=states.Count)
 {
 //to prevent error out of bounds, could be set to states.Count-1 or 0 ins$$anonymous$$d..
 return;
 }
 foreach(bool state in states)
 {
 state=false;
 }
 states[p_state]=true;
 }

Follow this Question

Answers Answers and Comments

123 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

Related Questions

How to make characters follow player like Earthbound? 0 Answers

Want to make GameObject follow another GameObject's path Unity3D 1 Answer

Use trail renderer for path following? 2 Answers

Make NPC follow player when seen? 2 Answers

NPC flying towards me!!! 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