random walker

is it possible to modify this script so that it still preforms the random walking but if it gets too far away from a certain object it comes back?

var ground: Transform;
var gravity: Vector3;
var speed: float;

var motionDir: Vector3;
var ctrl: CharacterController;

//=========================================

function Start() {
	ctrl = GetComponent(CharacterController);
	NewDirection();
}

function Update () {
	ctrl.Move((motionDir * speed + gravity) * Time.deltaTime);
}

function OnControllerColliderHit(collision: ControllerColliderHit) {
	if (collision.transform != ground) {
		NewDirection();
	}
}

function NewDirection() {
	motionDir = (new Vector3(Random.value - 0.5, 0.0, Random.value - 0.5)).normalized;
	transform.rotation = Quaternion.LookRotation(motionDir);
}

thanks

Do you mean you want the walker to return to the target after it has got a certain distance away or just that you want it to stay within range?

I would actually need one for both. one to go from a target to a certain distance to a random point then return.

then one to have a partol stay within a certain distance of a stationary object.

make sense.

You might actually be able to achieve both goals with Random.InsideUnitCircle now I come to think of it. This function returns random Vector2 values inside a circle centered at <0,0> with a radius of one unit. You can multiply the returned vector by a float value to get a larger circle (ie, if you multiply by two, the circle’s radius is two units, etc) and add another vector to it to move it to a different position:-

function RandomPointInRadius(centre: Vector3, radius: float) {
    var result: Vector3 = centre;
    var rand: Vector2 = Random.insideUnitCircle * radius;
    result.x += rand.x;
    result.z += rand.y;
    return result;
}