Endlessly Spinning Drone
I Have a Drone that I want to Wander when not following the player but when I enable Wander It just spins around in circles and moves violently around the map. I tried getting it to wait after it moves so it moves better but that didn't seem to have affected it. Any Suggestions?
using UnityEngine;
using System.Collections;
public class ai_followPlayer : MonoBehaviour {
public Transform Player;
public float MoveSpeed = 4;
public float MaxDist = 10;
public float MinDist = 5;
public bool Wander;
public float walkSpeed;
public float seconds;
void Start()
{
StartCoroutine(wait());
}
void Update()
{
if (Wander)
walk();
else
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
}
}
}
void walk()
{
float turnAmount = Random.Range(-360, 360);
transform.Rotate(0, turnAmount, 0);
transform.position += transform.forward * Time.deltaTime * walkSpeed;
wait();
}
IEnumerator wait()
{
yield return new WaitForSeconds(seconds);
}
}
Comment
Best Answer
Answer by conman79 · Nov 29, 2016 at 10:42 PM
The main problem here is that you are setting a new rotation every Update() frame. You want to set a new rotation after a certain amount of time. Something like this:
using UnityEngine;
using System.Collections;
public class ai_followPlayer : MonoBehaviour {
public Transform Player;
public float MoveSpeed = 4;
public float MaxDist = 10;
public float MinDist = 5;
public bool Wander;
public float walkSpeed;
public float seconds;
private float turnAmount = 0f;
void Start()
{
StartCoroutine(SetNewRotation());
}
void Update()
{
if (Wander)
walk();
else
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
}
}
}
void walk()
{
transform.position += transform.forward * Time.deltaTime * walkSpeed;
transform.Rotate(0, turnAmount, 0);
}
IEnumerator SetNewRotation()
{
while(true)
{
float turnAmount = Random.Range(-360, 360);
yield return new WaitForSeconds(seconds);
}
}
}