More than a line, enemy movement in Unity

Hal Brooks
2 min readJul 27, 2021

Objective: Add a new enemy movement to Unity game allowing circular motion.

Sequence from game showing enemy with circular motion which spirals down the screen.

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.

Variables required for both horizontal and vertical movement in Enemy script.

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.

Assignment of variables controlling enemy oscillations in void Start of Enemy script.

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.

Excerpt form void Update in the Enemy script controlling horizontal oscillation.

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.

Excerpt form void Update in the Enemy script controlling vertical oscillation.

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.

--

--