Hi all, I know similar questions have been asked but I am still struggling.
I have an NPC that randomly moves in the X and Z direction, and I want it to turn to the direction it is moving so as so be more realistic, but when I tried coding it, it just randomly rotates forever.
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;
void Start(){
latestDirectionChangeTime = 0f;
calcuateNewMovementVector();
}
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
if (transform.position.x > 0)
{
alien.transform.Rotate(0,90,0);
}
}
}
thank you in advance!