Zigging and Zagging the enemies.
Today we will create a zig-zag movement on our enemies to increase the difficulty of the game a little.
We will start by opening our ‘Enemy’ script and adding some new variables. We will create two private floats, one named ‘_frequency’ that is set to 3f, and the second named ‘_magnitude’ set to 2f. These variables will dictate the intensity and how often the zig turns to zags. Next, we will add a pair of ‘Vector3’ variables called ‘_position’ and ‘_axis’.
In ‘Start’ we will set our ‘_position’ to transform.position. We will set ‘_axis’ to transform.right.
Let’s create a new function called ‘DiagonalMovement’. This is for later on when we want some enemies to move in a straight line down and some to move in a diagonal.
In this function, we will add ‘_position’ with ‘Vector3.down’ then multiply ‘Time.deltaTime’ and multiply all that by ‘_enemyMovementSpeed’. We will then set our ‘transform.position’ equal to ‘_position’ plus our ‘_axis’ then multiply that by ‘Mathf.Sin’. The parameters of Sin will be Time.time multiplied by our ‘_frequency’, then we will multiply the whole thing by ‘_magnitude’. The Mathf.Sin is what will cause the zig zags to happen. When the frequency variable is met, the enemy will be told to move the opposite way.
After that, we will write an if statement that will reset the enemy at the top of the screen if it reaches the bottom of the screen. It’s exactly the same as the if statement in ‘CalculateMovement’, with one addition. We will add ‘_position’ is equal to ‘transform.position’.
That’s all for the code. Let’s just comment out our ‘CalculateMovement’ function in ‘Update’ for now, until we get different enemy types created. Let’s now put our ‘DiagonalMovement’ function in ‘Update’ for now to test things out.