Created
October 31, 2017 00:32
-
-
Save Templar2020/951380e54dd865a73120729985202b12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = Mathf.Clamp(heading - maxHeadingChange, 0, 360); | |
var ceil = Mathf.Clamp(heading + maxHeadingChange, 0, 360); | |
heading = Random.Range(floor, ceil); | |
targetRotation = new Vector3(0, heading, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment