Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active July 15, 2023 19:43
Show Gist options
  • Save mminer/1331271 to your computer and use it in GitHub Desktop.
Save mminer/1331271 to your computer and use it in GitHub Desktop.
Unity script to simulate a wandering behaviour for NPCs.
using UnityEngine;
using System.Collections;
/// <summary>
/// Creates wandering behaviour for a CharacterController.
/// </summary>
[RequireComponent(typeof(CharacterController))]
public class Wander : MonoBehaviour
{
public float speed = 5;
public float directionChangeInterval = 1;
public float maxHeadingChange = 30;
CharacterController controller;
float heading;
Vector3 targetRotation;
void Awake ()
{
controller = GetComponent<CharacterController>();
// Set random initial rotation
heading = Random.Range(0, 360);
transform.eulerAngles = new Vector3(0, heading, 0);
StartCoroutine(NewHeading());
}
void Update ()
{
transform.eulerAngles = Vector3.Slerp(transform.eulerAngles, targetRotation, Time.deltaTime * directionChangeInterval);
var forward = transform.TransformDirection(Vector3.forward);
controller.SimpleMove(forward * speed);
}
/// <summary>
/// Repeatedly calculates a new direction to move towards.
/// Use this instead of MonoBehaviour.InvokeRepeating so that the interval can be changed at runtime.
/// </summary>
IEnumerator NewHeading ()
{
while (true) {
NewHeadingRoutine();
yield return new WaitForSeconds(directionChangeInterval);
}
}
/// <summary>
/// Calculates a new direction to move towards.
/// </summary>
void NewHeadingRoutine ()
{
var floor = transform.eulerAngles.y - maxHeadingChange;
var ceil = transform.eulerAngles.y + maxHeadingChange;
heading = Random.Range(floor, ceil);
targetRotation = new Vector3(0, heading, 0);
}
}
@BaslaelWorkineh
Copy link

why does the character always move to the edge of the terrain?????????????

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment