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);
}
}
@collinticer
Copy link

i tried this script, but it just moves to a wall and stands there.

There isn't anything in this script that would handle a collision with a wall. This script simply moves in a direction for 1 second (default timing), changes direction, and then moves in that new direction, and repeat.

That said, after the collision with the wall, after a second or so it should choose a new direction and continue on.

You could also handle the collision directly. Since this wander script uses a character controller, you will likely need to make this new functionality as part of a child gameobject so that it can have a rigidbody associated to it, as Rigidbody and CharacterController often do not work well together on the same single gameobject.

So the parent gameobject, the one with the Wander script, should look something like this.

image

The new child gameobject should have a collider of some sort set to IsTrigger as well as a Rigidbody. On the Rigidbody you will likely want to disable gravity, and constrain x, y, and z of both the position and rotation. Here's what mine looked like.

image

On this child gameobject, create a new WandererCollisionTrigger.cs file and attach it. Here's that script. This will look at its parent game object, find the parents Wander class, and call the NewHeadingRoutine() anytime this child object detects a collision using OnTriggerEnter() callback.

using UnityEngine;

public class WandererCollisionTrigger : MonoBehaviour
{
    Wander wanderComponentOfParent;

    void Start()
    {
        wanderComponentOfParent = transform.parent.gameObject.GetComponent<Wander>();
    }

	void OnTriggerEnter( Collider collider )
	//void OnCollisionEnter( Collision collision )
	{
		Debug.Log( "colliding with something" );
		wanderComponentOfParent.NewHeadingRoutine();
	}
}

And, just in case, here is my "wall" gameobject - which is just a cube with a collider.

image

This should make it so when your character collides with a wall, it will choose a new direction. Keep in mind though that this could still result in a new direction that continues to collide with the wall.

Hope this helps!

@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