Thursday, July 2, 2015

Tutorial: Basic, Basic, AI

This is a very simple AI. It will just follow the player around.



This script will rely on intrinsic classes to the Unity engine, namely: TransformVector3 and CharacterControler. The float value is self explanatory, it will be the speed of the chase bot. There are two Vector3 variables: distanceFromPlayerTarget and my_Velocity. The first one my_Velocity is used by the chase bot to give it direction as it moves. distanceFromPlayerTarget is used to judge the distance from the player. Finally, the Character Controller chase_AI is what allows NPC to move, access animations and so on.

I'll explain the code in the Update() so you get an idea of how it works. We need our bot to know how far away our player is, so we take the players position by calling the .position method and we subtract from that value the position in world space with: transform.position; Now we need to normalize this Vector3. Why? Well, currently the Vector is giving us the length of the distance, we want direction. So we call the normalize to change the value to Vector3(0,01) rather than what ever its current value was.
Next we have to give velocity to out bot, we do this by taking the direction of the player we just normalized and multiply by the chase speed. Now with this we can make the bot move. So we call the character controller and call the .Move(), we have to pass the my_Velocity and multiply it by Time.deltaTime.

Make a new scene. Add in the first person controller(its a capsule)that unity provides. Add three or so cylinders. Attach your Chase script to the cylinders, also add character controllers to each cylinder.
Next drag the First Person Controller from the hierarchy to the Target_Player field, next drag the Cylinder from the hierarchy to the Chase_AI field. Now change the Chase Field value from zero to what ever you want. Start small though, these bots can be very fast.



You can play around with this. Add in conditionals to the distance from player and have the bots chase if the player is a particular distance from the chase bot. You can also add collider boxes around the scene have them correspond to particular chase bots, if the player passes through them have the bots chase the player.

Drive link:
Chase.cs

No comments:

Post a Comment