- Home /
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?
Answer by Joshua · Apr 29, 2011 at 02:53 PM
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 ins$$anonymous$$d 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.
Yeah. The thing is the way the AI follows the player around is they float over the player's shoulders. So basically they move and rotate wherever the player moves and rotates. Like little body guards. Just when the player rotates too close to a wall or any object the AI moves straight through like it's air. I have the AI detecting collisions while branched off and chasing enemies but that only checks for things ahead of the AI not in any other direction. And at that point they aren't moving through objects due to deactivating the follow commands and using Character Controller. Thoughts?
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!