Upgrading the chasing state of soldiers
Here is a part of the code I use for the AI of the soldiers. The green sentence is the old one, and the white one is the new one.

Let's break them down

First of all, I'm not a pro at programming, I'm still learning so what I do may not be the most efficient way to do it, but it works!

Old line of code :


if (!attacking && Mathf.Round(distance) <= distance_chase)




chase_chase() = the soldier will go on state "chase", so he will chase the player

if();= the condition "if" is true only if what is between "(" ")" is true. In that case the soldier will go on state "chase" only if  (!attacking && Mathf.Round(distance) <= distance_chase ) is true.

attacking= if the soldier is attacking the player, and !attacking means the opposite of that : the soldier isn't attacking the player.

&&= and

Mathf.Round()= we round the number inside "(" ")"

distance= it is a custom value that I describe elsewhere in the code, it is the distance between the soldier and the player.

<= = is inferior or equal

 distance_chase = a custom value that I can change for each soldier. I decide at what distance they will chase the player, it may be 1 meter, 5 meters etc...

Recap : If the soldier is not already attacking the player, he will check the distance between him and the player. If this distance is inferior or equal to the custom value I set, the soldier will chase the player. If it is superior to the custom value then the soldier will stay in his current state which is "patrolling".

Ok so this line of code worked well except for one thing. Can you guess what's the problem =D?

It comes from the distance value. When it calculates the distance between the soldier and the player it is on x (horizontal) and on y (vertical) axis.

So I decided to change the code, here is the new one :

if (!attacking && Mathf.Round(distance) <= distance_chase && Mathf.Abs(perso_chase.position.y - rb.position.y) <1))




Mathf.abs()= take the absolute value of what is inside "(" ")".

perso_chase.position.y = the  y (vertical) position of the player

rb.position.y= the y (vertical) position of the soldier.

Okay so here I added a condition.  Before going into chasing mode, the soldier will compare his y position and the players. If there is less than 1 unit between the two (and the other conditions are true) he will chase the player. 

And that's it =D. The unit 1 is a test, maybe I'll have to change it to 1.3 or 0.8 for some soldiers, I'll see.

Thanks for reading ;)