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
0
Question by SSpecks · Feb 27, 2020 at 07:47 PM · aifollownpcfollow playerbox collider

Make NPC follow player when seen?

Hi all, I am making a horror game with a random walking NPC. When the NPC sees the character, (when the player goes in range of the NPC's attached box collider), I want the NPC to start following the player for 10 seconds. The commentsalt text for the code are at the bottom of my script, the rest is the random walking I coded.

 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;
  
     
     void Start(){
         latestDirectionChangeTime = 0f;
         calcuateNewMovementVector();
     }
  
     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);
         
         
        
         // 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
              */
         }}}}

I attached an image of that the box collider will look like. I have walls in the game, and want to make sure that the collider cannot "see" through walls also. Thank you so much in advance!

screenshot-9.png (141.7 kB)
Comment
Add comment · Show 1
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 MacMC · Feb 27, 2020 at 08:13 PM 0
Share

using a box collider is probably the wrong approach. Try using a Raycast ins$$anonymous$$d (it's even more intuitive for things like crouching behind objects, seeing the player through peep holes, etc.) whereas a collider will always prove somewhat troublesome.

 //pseudo-code  
 
 Update()
 
 //get angle from Alien's forward direction to the player's position
  Vector3 targetDir = player.position - transform.position;
         float angle = Vector3.Angle(targetDir, transform.forward);
        if (angle < 30f)
       {
        // limiting the field of view will imitate a "zone" in which he can see in front of him.

 // set a distance for him to look, so he can't catch the player infinity miles away
   if (Vector3.Distance(player.position, transform.position) < 15f)
         {
            TryFindPlayer();
            }
       }
 
 TryFindPlayer()
 {
 Vector3 directionToPlayer = (player.position - transform.position).Normalize();
 
  if (Physics.Raycast(transform.position, directionToPlayer, out hit, maximumViewDistance)
         {
             Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
             Debug.Log("Player has been spotted");
         }
 }

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by LightMaster905 · Feb 27, 2020 at 08:08 PM

You could try to use navmesh agents and when you want it to stop moving just use NavMeshAgent.ResetPath()

Try this:

 //Create a few more variables 
 private GameObject player;
 private Transform target;
 private float distance;
 public float sight;
 
 //Inside Start:
 player = GameObject.FindGameObjectWithTag("Player")
 target = player.GetComponent<Transform>();
 
 //Inside Update:
 
 distance = Vector3.Distance(target.position, alien.transform.position);
 
 if (distance <= sight) {
     alien.agent.SetDestination(target);
 }
 

You should be able to figure everything else out. Make sure you set your ground to static and under navigation click the bake button. Also add a NavMeshAgent into the enemy.

Comment
Add comment · 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
0

Answer by Triggerly · Feb 28, 2020 at 02:34 AM

Maybe you can set the collider to trigger then add a

 void OnTriggerEnter(Collider other)
 {
     // Start Following Player by getting the player coordinate in Update()
 }
 

Comment
Add comment · 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

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

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

Make an NPC follow player? 1 Answer

Having a friendly character follow player 0 Answers

NPC code, works great, besides them being in the ground. 2 Answers

Sidescroller NPC follows Player 0 Answers

AI Enemy Follow Player 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