How to prevent team AI from moving through everything?

Hello! I am making some AI and I have my teammate AI following the player with this code.

var targetFollow : Vector3 = player.TransformPoint(Vector3(4, 0, -6));
                transform.position = Vector3.SmoothDamp(transform.position, targetFollow, velocity, dampRot);
                transform.rotation = Quaternion.Slerp(transform.rotation, player.rotation, Time.deltaTime * 10);

That works great for following the player the way I want it to. The only issue now is the team AI moves through everything. I'm using a character controller so when the AI needs to branch off and attack an enemy they can move smoothly by use of the character controller. Any idea as to how I can fix the moving through?

1 Answer

1

You could use Spherecasting to see if there is something in front of the AI. If there is something in front of him and distance is less than x have him move a bit to the left/right and check again.

Here is an example I found checking if something is above the character:

function Update () {
    var hit : RaycastHit;
    var charCtrl : CharacterController = GetComponent(CharacterController);
    var p1 : Vector3 = transform.position + charCtrl.center + 
                Vector3.up * (-charCtrl.height*0.5);
    var p2 : Vector3 = p1 + Vector3.up * charCtrl.height;
    // Cast character controller shape 10 meters forward, to see if it is about to hit anything
    if (Physics.CapsuleCast (p1, p2, charCtrl.radius, transform.forward, hit, 10)) {
        distanceToObstacle = hit.distance;
    }
}

Thank you for the reply but is there any way to have a collision instead of just moving around it?

I believe theres a way to make the AI create a path before moving, but I dont know how. If you make him test a collision and then go Left/Right he'll look like a blind man.

Child an empty gameobject to the AI. Reset it's transform. Add a capsule collider and scale it. Through code, turn it on/off when following/not following.

Alrighty. Simple solution. I'll try it and let you know how it goes. Thank you!

That didn't work. For some reason that follow code I put on is causing the collisions to be ignored. I take that off and it collides. That's odd.