- Home /
AI patrolling script
Hi, I have this script, and I was trying to make it rotate 180 grades once he gets to one patrol point,but I'm lost, I hope you can help me, thanks.
public class POLICEscript : MonoBehaviour {
public Transform[] patrol;
private int Currentpoint;
public float moveSpeed;
void Start()
{
transform.position = patrol [0].position;
Currentpoint = 0;
}
void Update()
{
if(transform.position == patrol[Currentpoint].position)
{
Currentpoint++;
}
if(Currentpoint >= patrol.Length)
{
Currentpoint = 0;
}
transform.position = Vector3.MoveTowards (transform.position, patrol [Currentpoint].position, moveSpeed * Time.deltaTime);
}
Answer by Cherno · Sep 15, 2014 at 10:51 PM
First of all, I would suggest using a Vector3[] as your patrol coordinates, no reason to use a transform, is there? Anyway, since an object's position will almost certainly never be exactly the same as another one's if it hasn't been moved there by setting the values by hand, you will be better off checking the Vector3.distance between the character and his next patrol position. Once he gets within a certain distance, like 0.5f units, he has has more or less reached it and can continue on to the next. The threshold could of course be made much smaller, it's worth experimenting. Just don't make it too small (0.00xxx) or it will never be reached.
You just have to modify the line like this:
if(Vector3.Distance(transform.position, patrol[Currentpoint]position) < 0.5f) {
Currentpoint++;
}
As for rotating, there are several ways to do it, one is explained here : http://blog.anthonybaker.me/2010/09/rotating-your-character-in-unity3d.html
thank you so much Cherno, but I'm really stuck with the rotating thing. I hope you could help me with this
public float rotateSpeed = 2.0f;
private bool rotating;
void Update() {
StartCoroutine(TurnTowards(-transform.forward));
}
IEnumerator TurnTowards(Vector3 lookAtTarget) {
if(rotating == false) {
//Vector3 direction = lookAtTarget - transform.position;//this can be deleted, it's never used :P
Quaternion newRotation = Quaternion.LookRotation(lookAtTarget - transform.position);
newRotation.x = 0;
newRotation.z = 0;
for (float u = 0.0f; u <= 1.0f; u += Time.deltaTime * rotateSpeed) {
rotating = true;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, u);
yield return null;
}
rotating = false;
}
}
You are welcome. I just noticed that I left the direction variable in the CoRoutine by mistake, it's never used so I will edit my post to reflect that.
Your answer
Follow this Question
Related Questions
How to remove z axis control from script 1 Answer
Patrol system not working? Ignoring points(?) 0 Answers
npc patrol and chase 1 Answer
problem with my script need help 2 Answers