- Home /
How can I make a script to make enemy wander, chase, and kill player
I'm trying to make a simple script to make an enemy wander randomly, follow the player when the player is within a certain range of it, and kill the player when the two make contact while using it's attack animation. How can I do this?
Answer by UnityNoob123 · Sep 06, 2017 at 05:15 AM
@jcolucci93 In order to achieve this I would recommend watching this video/video series: https://www.youtube.com/watch?v=7Kk1D4v3vIg∈dex=14&list=PLwyZdDTyvucyAeJ_rbu_fbiUtGOVY55BG There are some things you need to do in the Unity Editor such as Navigation Baking and working with the Nav Mesh Agent, and this video covers it nice and quick. As far as wandering around I wrote a script a while back with this tutorial and implemented my own wander function. In the video the guy will show you how to make the SetNavDestination function. Basically the WanderAround function calls another function that picks a random point within the set wander radius, and sets that point to the destination while setting a random delay so the ai does not keep picking a new position every second. If you are just starting out in Unity, which it seems like, this can look confusing and if you have any questions just ask. For the most part try writing your own code first and not just copy others, even if you do not succeed it still helps I find.
private bool canWander = true; private float wanderRadius = 30f;
public void SetNavDestination (Transform destination) {
if (GetComponent<ZombieStats> ().Health > 0) {
agent.SetDestination (destination.position);
transform.LookAt (targetTransform);
agent.speed = 3.5f;
}
}
void WanderAround () {
if (targetTransform == null && canWander == true) {
agent.speed = 0.5f;
Vector3 _newPos = RanNavSphere (myTransform.transform.position, wanderRadius, -1);
agent.SetDestination (_newPos);
canWander = false;
float _ranNum = Random.Range (0, 20);
StartCoroutine (WanderDelay (_ranNum));
}
}
Vector3 RanNavSphere (Vector3 _origin, float _dist, int _layerMask) {
Vector3 _ranDirection = Random.insideUnitSphere * _dist;
_ranDirection += _origin;
NavMeshHit _navHit;
NavMesh.SamplePosition (_ranDirection, out _navHit, _dist, _layerMask);
return _navHit.position;
}
IEnumerator WanderDelay (float _ranNum) {
yield return new WaitForSeconds (_ranNum);
canWander = true;
}
Your answer
Follow this Question
Related Questions
Show only selected enemy's health bar 1 Answer
EnemyAI C# Error 1 Answer
If Enemy Health (< 10) then Exp (+10)? 1 Answer
Making enemy push player 1 Answer
Hurt Player if close to Enemy! Need Help 4 Answers