More than a line, enemy movement in Unity
Objective: Add a new enemy movement to Unity game allowing circular motion.
To allow the basic _enemyID of 0 to move in a spiral pattern, the Enemy script must be modified. The _distanceX and _distanceY variables control, respectively, the side to side and forward and back motion. The variable _rotX is used to control the direction of the rotation.
The _rotX is assigned in void Start for oscillating enemies, i.e. ID 0 or 1. The function _rotX = 1 -2*Random.Range(0,2) results in a equal probability of either a 1 or -1.
There already is an _enemyID of 1 that oscillates back and forth, so adjusting the if statement to be _enemyID ≤ 1 provides enemy ID 0 with the back and forth oscillation, see below. The oscillations are created using the Mathf.Sin function previously created to define _distanceX. Changing the sign of the transform.Translate with the _rotX allows this oscillation to be either clockwise or counterclockwise.
Similar code is used to control the vertical motion, as shown below; however, Mathf.Cos is used with the same frequency and phase to create circular motion. The spiral is created by adding a constant speed to _directionY, thus the cosine function slows or accelerates the general downward speed of the enemy, allowing it to briefly travel backwards.
Given that the frequency and phase are also varied this produces complex and variable movement for the enemies. The basic enemy now spirals down the screen, dodging to the left and right; a menace to the player.