Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active July 15, 2023 19:43
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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);
}
}
@euriahmoore4
Copy link

do I just attach it to my character or is there steps I need to take

@mminer
Copy link
Author

mminer commented Jun 25, 2021

@euriahmoore4: Just attach this to your character and it should work. It requires that your game object have a CharacterController component, but it'll automatically add one if needed.

@dmcrider
Copy link

dmcrider commented Oct 12, 2021

How would you implement turning around when the NPC runs into a wall, for example?

@mminer
Copy link
Author

mminer commented Oct 16, 2021

@dmcrider: To handle walls, my first instinct would be to add a collider to my NPC and change the transform's rotation in OnCollisionEnter. To face the NPC in the opposite direction I'd then use collision.contacts[0].normal.

@GHU09
Copy link

GHU09 commented Nov 23, 2022

2022-11-23.21-26-54_Trim.mp4

I atached it to my character but the only thing it does is turn around it doesnt move around.

@collinticer
Copy link

2022-11-23.21-26-54_Trim.mp4

I atached it to my character but the only thing it does is turn around it doesnt move around.

I've attached this in my own game and it just works so it seems like there's something specific to your project that is causing that. I would suggest trying to increase the speed variable. If the scale of your objects is off it could be that they are moving but the scale is too small to notice.

If you play your project you can change the speed variable in the inspector and it will revert back once you quit play mode.

@GHU09
Copy link

GHU09 commented Dec 29, 2022

2022-11-23.21-26-54_Trim.mp4
I atached it to my character but the only thing it does is turn around it doesnt move around.

I've attached this in my own game and it just works so it seems like there's something specific to your project that is causing that. I would suggest trying to increase the speed variable. If the scale of your objects is off it could be that they are moving but the scale is too small to notice.

If you play your project you can change the speed variable in the inspector and it will revert back once you quit play mode.

Ok im gonna try that, could it also be that the script just Doest work in the unity version i use?

@collinticer
Copy link

collinticer commented Dec 29, 2022

It really shouldn't be an issue with the version you're using. This all appears to be baseline Unity functionality. And if it were an issue with the code not being supported in your version, you would receive a red error message in the Unity debug log as well and your project likely wouldn't run at all.

You can also watch the position of your game objects transform component. If it's moving at all, even if it's not noticeable, you should still be able to see the numbers changing there as well.

@Fguy123
Copy link

Fguy123 commented Feb 25, 2023

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

@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