AI movement using Character Controller, turning problem

I’m creating a Pacman game. The movement of the enemy AI is random for now. I’ve created code that would determine if obstacles are in front, left or right from the enemy using Raycasting. If the enemy can, he’ll randomly walk in one direction that’s available (not counting backwards). When the unit decides to go left/right, I try to turn the character since the Raycasting is done via Vector3.Right or Vector3.Left. But somehow, the unit doesn’t seem to turn.

Here is some code:

function MoveDirection(dirWay) {
	var direction : Vector3;
	if (Time.time > nextUpdate) {
		if (dirWay == 0)
			direction = transform.position + Vector3.forward * 2;
		if (dirWay == 1)
			direction = transform.position + Vector3.left * 2;
		if (dirWay == 2)
			direction = transform.position + Vector3.right * 2;
        nextUpdate = Time.time + (Random.value * howLong);
        //direction = Random.onUnitSphere;
        direction.y = 0;
        direction.Normalize ();
        direction *= howFast;
        direction.y = 1.5 - transform.position.y;
    }
    var controller = GetComponent(CharacterController);
    controller.transform.LookAt(direction*10);
    controller.Move(direction * Time.deltaTime);    
}

What am I doing wrong?

EDIT: Two of the four ghosts walk in a corner and get stuck there, while the other two take three turns and get stuck in a corner there. They always perform the exact same behaviour every run even though it should be random.

There are several errors in the logic:

  • direction must be declared outside any function in order to hold its value until nextUpdate;

  • don’t add transform.position to direction: adding it will generate a point in the direction to move, what’s needed only in the LookAt argument;

  • there’s some weird code after the last if that’s screwing up direction.

    // declare direction outside Update, so that it will keep the last direction:
    private var direction = Vector3.zero;

    function MoveDirection(dirWay) {
    if (Time.time > nextUpdate) {
    if (dirWay == 0)
    direction = Vector3.forward;
    if (dirWay == 1)
    direction = Vector3.left;
    if (dirWay == 2)
    direction = Vector3.right;
    nextUpdate = Time.time + (Random.value * howLong);
    direction *= howFast;
    }
    var controller = GetComponent(CharacterController);
    // LookAt need a point, so you add transform.position here:
    controller.transform.LookAt(transform.position+direction);
    controller.Move(direction * Time.deltaTime);
    }