Enemy chaser mechanic
The objective is to create an enemy that “chases” the player when it is nearby.
There will be 2 different mechanics:
- Move downwards and rotate while looking for player
- If player is found, it will look at it and will chase it
Move downwards and rotate while looking for player
For the first mechanic, we will use
InverseTransformDirection will make the enemy to move down in accordance with world space. It transforms the local
Vector2.down to global.
Because if it is not set up this way, the enemy will move down depending on its rotation, and that is not the desired behaviour.
rotateValue is set to 1, but it can be set as desired. It is the amount of degrees we want the enemy to move each frame.
xFlip is intended to swich the rotation to right or left.
The last line is the enemy’s rotation on its z axis.
If player is found, it will look at it and will chase it
First, we need to scan for player
playerHit2D is a
Physics2D.OverlapCircle checks if a Collider falls within a circular area
playermask is a layer. It is different from a tag.
So, the code will check if the object in the circle collider has the
PlayerMask layer in it. If so, it will execute the code.
When that happens, it will move to target and look at it
Rigth now, the
transform.up in the enemy looks like this
but if the code is
transform.up = (target.position — transform.position), it would look like this