Wandering AI Rotation

Hey there! I am trying to implement the wandering AI steering behavior, but I am having a problem with the rotations. Here is my code:

static int i;
    private static void AIWander(Rigidbody _rb) {
        //Add a small randomness to the targets position   
        float frameJitter = wanderJitter * Time.deltaTime;

        if (i >= 50) {
            //Only change direction every fifty updates
            wanderTarget += new Vector3((UnityEngine.Random.Range(-1f, 1f) * frameJitter), 0, (UnityEngine.Random.Range(-1f, 1f) * frameJitter));
            wanderTarget.Normalize();
            wanderTarget *= wanderRadius;
            i = 0;
        }

        //Move the target in front of the ai
        Vector3 targetLocal = new Vector3(wanderTarget.x, 0, wanderTarget.y + wanderDistance);
        Vector3 targetWorld = _rb.transform.TransformPoint(targetLocal);

        //Apply
        AISeek(_rb, targetWorld);
        i++;
    }

private static void AISeek(Rigidbody _rb, Vector3 _targetPosition) {
        //Find the direction towards the target and proceed to move that way
        Vector3 desiredVelocity = ((_targetPosition - _rb.position).normalized) * aiSpeed;

        //Apply
        _rb.MovePosition(_rb.transform.position + new Vector3(desiredVelocity.x, 0, desiredVelocity.z) * Time.deltaTime);
        _rb.transform.LookAt(new Vector3(_targetPosition.x, _rb.position.y, _targetPosition.z));
    }

I know that my problem stems from me setting the local target to world using the rigidbody in Wander, but then rotating that rigidbody in seek every udate. How can I get the ai to still look where it is going while still incrementing the wander correctly? Thanks

This is too vague. Is it not turning at all? Is it spazzing out? Is it turning the wrong way? Consistently the wrong way? Only sometimes the wrong way? When is it wrong? etc. etc. ec.

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

Sorry, I clarified a bit more at the bottom of the post but here is the problem. In AI Wander I am first modifying the target locally and then setting its world position. I’ve solved it now anyways, thanks.

1 Like