- Home /
Enemy Patrol - Random Walk
I have my AI script already and its fairly simple, I wanted to add a code where the enemy can look at its own position and every couple seconds walk a little bit in a random direction.. I just dont know how to do it, way points and paths wont really work for my game as im going to be respawning and killing these mobs so I wanted to make it simple!
THANKS IN ADVANCE
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
private Transform myTransform;
void Awake() {
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance(target.transform.position, transform.position);
Debug.Log(distance);
if(distance > 10) {
animation.Play("idle");
}
if(distance < 10) {
Debug.DrawLine(target.position, myTransform.position, Color.red);
//look at target/rotate
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
//move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
animation.Play("walk");
}
}
}
Answer by sparkzbarca · Jan 14, 2014 at 01:33 PM
just use random
you can use random.unitcircle to get the x and z portions
then multiply that by a random number again which is from 0 to X where X is the max distance to walk before checking again.
Finally add that to current mob position to get the final position
so
vector2 Temp = random.unitcircle;
TempDistance = random.range(0, 10);
Temp = Temp * TempDistance;
vector3 FinalTemp = new vector3(Temp.x, 0, Temp.y);
MovePos = mob.transform.position + FinalTemp;
//move mob to movepos
sorry I dont completly understand how to add this into my script or how it works.. can you explain a bit more?
Your answer
Follow this Question
Related Questions
Enemies walk to waypoints and stop in specific ones 0 Answers
Enemy Patrol 1 Answer
How do I make the enemy stop walking and shoot the player? 1 Answer
How To Make Enemy Move Around 0 Answers