Dynamic Wander A.I.

For a project I need to make use of a number of AI techniques, and I’m stuck on dynamic wander. The purpose of this is to create a circle a certain distance in front of the player’s orientation and then move to that point and repeat. My current code only seems to move the player in all directions instead of just mostly forward.

void wand(){
	Vector3 objPos = new Vector3(transform.position.x + (transform.forward.x*10),0,transform.position.z + (transform.forward.z*10));
	Vector3 source =  (Random.insideUnitSphere * 10);
	targetLocation = new Vector3(source.x+objPos.x,0, source.z + objPos.z);

}

Your algorithm isn’t correct. You should be using a point on the perimeter of a circle (for 2D movement as you described). You should not be picking a random point each frame, rather you should be moving a random distance around the perimeter of the circle.

The algorithm typically runs like this

  1. Offset the target position from the current target position by a random amount
  2. Project the target position back onto the circle centred on your vehicle
  3. Project the circle in front of the vehicle.

Code to come when I get a moment.

Edit: Code as follows. Should work, untested.

Vector3 steeringDirection = new Vector3();
float circleOffset = 5;
float circleRadius = 2;
float maxJitter = 0.5f;

void Wander (){
    Vector3 targetPosition = steeringDirection - transform.forward*offset;
    targetPostion = new Vector3 (targetPosition.x + Random.Range(-maxJitter, maxJitter), 0, targetPosition.z + Random.Range(-maxJitter, maxJitter));
    targetPosition.Normalise();
    targetPosition = targetPosition * circleRadius;
    steeringDirection = targetPosition + transform.forward*offset;
}

The output from this function goes into steeringDirection. You could easily pass it back as a return parameter instead.

You probably want to use invoke repeating or some such to provide frame rate independence. Otherwise this function will produce noticeably different behaviour based on the frequency of recalculation of the steeringDirection.