Sun Guangdong 2015.8.15
First, Enemy Aim Ai
Purpose: The main purpose of this article is to let you know about how to use the Enemy aim Ai. You will get the result:
Enemy aim AI is very useful when you want enemies to keep tabs on the player. Proper targeting of objects in real-world scenarios takes time, so the enemy will take some amount of time before it locks on the target system.
This effect can create a lerping rotation angle against the player's enemies. This situation is very useful in the case of action games, where the enemy follows, where the purpose is then to shoot the player. The concept of following the enemy was discussed earlier in the blog post. It is necessary to understand the concept of four-dollar numbers while pushing for the game.
Four-dollar rotation of the storage object, you can also calculate the value orientation. One can play the Euler angle directly, but there may be a case of universal lock.
Depending on the local coordinate system, if you rotate the Model X-axis, then its Y-and Z-axis experience gimbal locks are "locked" together.
Now back to our topic, given the following is a simple example to explain Enemy aim AI
Follow the steps given below.
1. Create cube will function in the player control
- Apply the appropriate material to its grid renderer as required
- Apply Targetmovementscript to Game objects
- Use cube as an object to move on to the player ' scommands.
TargetMovementScript.cs
public class Targetmovementscript:monobehaviour {public float targetspeed=9.0f;//speed at which the Object should Movevo ID Update () transform. Translate (Input.getaxis ("Horizontal") *time.deltatime*targetspeed,input.getaxis ("Vertical") *time.deltatime* targetspeed,0);}}
2. Create a enemy object, composed of arrows and cubes,
1. Apply the appropriate material to the cube.
2. Make the arrow sprite as a different object
3. Its direction is pointed out by cube. So here the arrow will act as the enemy's gun.
4. This arrow will point to the target object and it looks as if it was trying to lock the target
5, we can also manipulate the speed, the enemy will be able to lock target properties, as different enemies should be different difficulties, as well as different functions.
6, a tank should take more time to lock a soldier with a gun aimed at. So the speed at which one can lock the target should be different.
EnemyAimScript.cs
public class Enemyaimscript:monobehaviour {public Transform target;//target objectpublic float enemyaimspeed=5.0f;// Speed @ which enenmy locks on the targetquaternion newrotation;float orienttransform;float orienttarget;void Update () { Orienttransform = Transform.position.x;orienttarget = target.position.x;//to Check in which side is the target, i.e. Rig HT or left of this objectif (Orienttransform > Orienttarget) {//would Give Rotation angle, so, Arrow Points toward s that targetnewrotation = Quaternion.lookrotation (transform.position-target.position,-vector3.up);} else {newrotation = Quaternion.lookrotation (transform.position-target.position,vector3.up);}//Here we had to freeze Rotation along X and Y Axis, for proper movement of the arrownewrotation.x = 0.0F;NEWROTATION.Y = 0.0f; Finally rotate and aim towards the target direction using Code belowtransform.rotation = Quaternion.lerp (Transform.rot Ation,newrotation,time.deltatime * enemyaimspeed); AnotheR alternative//transform.rotation = Quaternion.rotatetowards (transform.rotation,newrotation, Time.deltaTime * enemyaimspeed);}}
7, Hierarchy and Scene View may be as given below
Remark:-
You can change your opponent's target and set the speed of the target.
A script can be used to understand this concept by allowing the X or Y axis to rotate.
You can add follow scripts to enemies to follow and target the player.
Instead of using Quaternion.lerp you can also use quaternion.rotatetowards to achieve the same effect.
Second, through the finite state machine to implement AI
Contents Objective Step-
1:set up the scene Step-
2:create and place Game Objects Step-
3:implement the boxmovement Script Step-
4:FSM modelled Script Step-
5:ai Script for the Box-
Purpose: The main purpose of this article is to give you an AI on how to use the finite state machine model in implementation.
Basic knowledge of FSM:
Implementing the AI finite in the game the state machine framework is perfect and produces great results without the need for complex code. It is a model that consists of one or more states. A single state can be active for a period of time, so the machine must be converted from one state to another to perform different operations.
Finite state machine frameworks are often used to manage, organize, and represent different states and execute streams, and it is very useful to implement AI in games. "Brain" is an enemy, for example, a finite state machine can be used: Each State represents an action, such as patrolling, Chase, evading or photographing, or any other kind of action.
AI FSMs works with Unity's animation FSMs, where an animated state will be changed to another compliant requirement. An AI FSM can be implemented by using a third-party plug-in like behavior, or it can be executed directly by the script.
To get the basic idea of a finite state machine framework, we will perform a tutorial in the simplest way, using the switch statement. Then we'll learn how to use a framework that makes AI implementations easy to manage and extend.
Please follow the steps below to perform a simple finite state machine.
Here we will have two box, where the player will control a box and the other will be controlled by the AI box. This AI-controlled box will be in chasing Chase state or patrolling patrol state, i.e. box will start chasing player box, once the player box comes in close to AI control Box. It will switch back to patrol state if the player is far enough away from the undefined vision.
Step-1: Set up the scene
With a flat and two box in the scene, as shown in the settings.
Step-2: Create and place Game Objects
Create an empty game object and use it as a wanderer point Wanderer Points. Place these empty game objects under, for you to select the plane around. Here the Blue cube is the AI cube and the red one is the player-controlled cube. Put them at a distance not far enough.
Step-3: Implement the Boxmovement Script
Implement the Boxmovement script to control the movement of the player's cube:
public class boxmovementscript:monobehaviour{public float speed = 0.1f;private Vector3 positionvector3;void Update () {initializeposition (); if (Input.getkey (Keycode.leftarrow)) {goleft ();} if (Input.getkey (Keycode.rightarrow)) {GoRight ();} if (Input.getkey (Keycode.uparrow)) {gotop ();} if (Input.getkey (Keycode.downarrow)) {Godown ();} Rotatenow ();} private void Initializeposition () {PositionVector3 = transform.position;} private void Rotatenow () {quaternion targetrotation = quaternion.lookrotation (Transform.position-positionvector3); Transform.rotation = targetrotation;} private void Goleft () {transform.position = transform.position + new Vector3 (-speed, 0, 0);} private void GoRight () {transform.position = transform.position + new Vector3 (speed, 0, 0);} private void Gotop () {transform.position = transform.position + new Vector3 (0, 0, speed);} private void Godown () {transform.position = transform.position + new Vector3 (0, 0,-speed);}}
Step-4: FSM modelled Script
To build an FSM model script:
public class Fsm:monobehaviour{//player transformprotected Transform playertransform;//next destination position of the Boxprotected Vector3 destpos;//list of points for patrollingprotected gameobject[] pointlist;protected virtual void Initi Alize () {}protected virtual void fsmupdate () {}protected virtual void fsmfixedupdate () {}void Start () {Initialize ();} void Update () {fsmupdate ();} void Fixedupdate () {fsmfixedupdate ();}}
Step-5: AI Script for the Box
Build an AI script as a box extension.
public class Boxfsm:fsm{public enum Fsmstate{none,patrol,chase,}//current state, the Box is Inpublic fsmstate Cursta Te;//speed of the Boxprivate float curspeed;//box Rotation speedprivate float currotspeed;//initialize the finite state ma Chine for the AI driven boxprotected override void Initialize () {curstate = Fsmstate.patrol;curspeed = 5.0f;currotspeed = 1.5f;//get the list of pointspointlist = Gameobject.findgameobjectswithtag ("Wandarpoint");//set Random Destination Poin T for the patrol state Firstfindnextpoint ();//get the target Enemy (Player) gameobject Objplayer = Gameobject.findgameobjec Twithtag ("Player");p Layertransform = objplayer.transform;if (!playertransform) print ("Player doesn ' t exist: Add one "+" with Tag named ' Player ');} Update each frameprotected override void Fsmupdate () {switch (curstate) {case FSMState.Patrol:UpdatePatrolState (); Break;case FSMState.Chase:UpdateChaseState (); break;}} protected void Updatepatrolstate () {//find another random PatroL Point on reaching the//point is Reachedif (Vector3.distance (transform.position, Destpos) <= 2.5f) {PR Int ("reached to the destination point\n" + "calculating the next point"); Findnextpoint ();} Check the distance with player Box//when the distance are near, transition to chase Stateelse if (vector3.distance (trans Form.position, playertransform.position) <= 15.0f) {print ("Switch to Chase State"); curstate = Fsmstate.chase;} Rotate to the target pointquaternion targetrotation = quaternion.lookrotation (destpos-transform.position); transform . rotation = Quaternion.slerp (transform.rotation, targetrotation, Time.deltatime * currotspeed);//go Forwardtransform.translate (Vector3.forward * time.deltatime * curspeed);} protected void Findnextpoint () {print ("Finding next Point"), int rndindex = Random.range (0, pointlist.length); float Rndra Dius = 5.0f; Vector3 rndposition = Vector3.zero;destpos = pointlist [rndindex].transform.position + rndposition;//check Range to Moveand decide the random point//as the same as Beforeif (Isincurrentrange (Destpos)) {rndposition = new Vector3 (random.range (-rndradius, Rndradius), 0.0f, Random.range (-rndradius, Rndradius));d estpos = pointlist [rndindex].transform.position + Rndposition;}} protected bool Isincurrentrange (Vector3 pos) {Float XPos = mathf.abs (pos.x-transform.position.x); float Zpos = Mathf.abs (pos.z-transform.position.z); if (XPos <= 8 && zpos <= 8) return True;return false;} protected void Updatechasestate () {//set the target position as the player Positiondestpos = Playertransform.position;//ch Eck the distance with player Box whenfloat dist = vector3.distance (transform.position, playertransform.position);//go BAC K to patrol as player are now too Farif (Dist >= 15.0f) {curstate = Fsmstate.patrol; Findnextpoint ();} Rotate to the target pointquaternion targetrotation = quaternion.lookrotation (destpos-transform.position); transform . rotation = Quaternion.slerp (transform.rotation, tarGetrotation, Time.deltatime * currotspeed);//go forwardtransform.translate (Vector3.forward * Time.deltaTime * curSpeed );}}
This script applies to the cube to follow the player, do not forget to tag the player tags as player and tag for Wandarpoint, now the script shown in Fsmupdate () will call the method, which is overridden in the subclass and it will be executed on each update ().
Here the switch case is implemented that will be used to perform the operation of the current state. So extending the AI is very simple simply by adding a new state. The Initialize () method is also overridden, and execution is invoked in the start () method. Updatepatrolstate () will be executed on each update, and when the current state is patrol around the patrol, it will also occur in Updatechasestate () when the player is in proximity to the AI Box. If the player enters the AI box while on patrol, the status will change to patrol, the same type of check is still in chase mode check if the player has been away from their field of view, then switch back to patrol state, check the status changes in each update.
Conclusion: FSM is easy to understand and implement, FSM can be used to execute complex AI. They can also represent the use of graphs that allow developers to easily understand, so developers can adjust, change, and optimize the end result. A function or method used by a finite state machine to represent state execution is simple, powerful, and easy to scale. You can use a stack-based state machine to ensure easy management and stable execution of the flow without negatively impacting code applications or even more complex AI. So make your enemies smarter using finite state machines to make your game a success.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Enemy AI within Unity