Objective: To give our newly created teleport enemy some different movement patterns!
This movement is going to have a mix of straight and angular movement depending on it’s spawn/respawn position and and it’s end position in which we will be using random Vector3 coordinates.
Let’s Create Some Code — Teleport Enemy
I have created a new script for this enemy called “TeleportEnemyBehaviour”.
Firstly we are going to need a speed variable for the enemy. We are also going to need a Vector3 variable that is going to store the enemies end position.
Next in Start() we are going to set the enemies starting and end position as a random X value (between -8f and 8f, screen boundaries). The spawn and end position will be 6f and -7f on the Y axis respectively and we can ignore the Z axis.
Lastly, we are going to call our CalculateMovement in the Update() method to ensure the enemy is constantly moving with the below code:
Let’s start by creating a new Vector3 variable that is going to handle the enemies movement direction. This is going to be equal to it’s current position less the _endPos as determined above. Then we need to make sure we are setting the magnitude to 1 by normalizing the direction. Lastly, we are going to assign the enemy players transform position to the direction multiplied by the _enemySpeed and Time.deltaTime to move in real time.
Next we are going to If check the enemies Y axis position and if it is below -6 then we are going to run the Respawn() method which is going to respawn the enemy back to the top of the screen with a new random position and it will also be given a new end position so the enemies angular movement will always change until it is killed.