2D Galaxy Shoot P2: New Enemy Movement!
For today's challenge, I implemented a new enemy movement!
The challenge was to create a new enemy movement type. The first thing I thought about was the zig-zag routine. Why not implement a movement where the enemy can randomly move right or left while going down?
So the first thing I did was separate the movement code from the enemy script into its own called “EnemyMovement.” What I did there was the first step in SOLID principles, the Single-Responsibility principle. All I want the enemy movement script to do is to handle movement.
To determine a type of movement, I went ahead to create an enum.
public enum EnemyMovemenType { Default, ZigZag, }
I want to control this in the inspector, so I initialized and declared the enum type:
[SerializeField] private EnemyMovemenType _enemyMovementType = EnemyMovemenType.Default;
Since I want to control the time when the enemy can switch from left to right, I created a coroutine.
private IEnumerator SideSwitcherRoutine()
{
_switchSideRate = Random.Range(2f, 5f); yield return new WaitForSeconds(_switchSideRate); _canSwitch = false;
}
I want to randomize a time for when the enemy can switch sides. The _switchSideRate
variable does this. It randomized a float value between 2 to 5. So this means that within 2 to 5 seconds, the enemy will switch.
In the movement function, called in the Update()
, I have conditions for each movement type.
if (_enemyMovementType == EnemyMovemenType.Default)
{
transform.Translate(Vector3.down.normalized * _speed * Time.deltaTime);
}
else if (_enemyMovementType == EnemyMovemenType.ZigZag)
{
if (!_canSwitch)
{
randomSide = Random.Range(1, 3);
_canSwitch = true;
} if (randomSide == 1)
transform.Translate((Vector3.down + _right).normalized * _speed * Time.deltaTime);
else if (randomSide == 2 || transform.position.x > leftRightEdge)
transform.Translate((Vector3.down + _left).normalized * _speed * Time.deltaTime);
}
If the movement type zig-zag is selected and _canSwitch
is false, we want to randomize the value to switch sides. We then set the _canSwitch
to true, so that the randomSide
variable doesn’t randomize on every frame. We restrict it until _canSwitch is set to false.
If the randomSide
variable equals one, then we move down-right. Else, if the randomSide
variable equals two, then we move down-left.
The 3-second gif doesn’t do it justice but it’s working!
I have to admit that this challenge had me pull out some hair! Not sure if it’s the inexperience, but my problem earlier had to do with the enemies randomly switching left and right in every frame. So I decided to add a bool for control.
For tomorrow’s challenge, I am not sure which one to pick! There are so many of them!
Thank you for stopping by!