- Home /
Other
Make an NPC follow player?
Thank 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
*/
}
}
}
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;
}
}
i updated the code. call it EnemyController and get rid of the walking script
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;
}