Creating New Enemy Movement
This tutorial will go over how to change up enemy movement adding two different enemy movement types diagonal and curved. This is all handled inside the Enemy script so head over there. First add three new variables. One to track the movement type so it will keep moving with the same pattern. One to for the movement directions. This has just been down in the past but will now include different options. The last variable is used to add the curve to the movement.
[SerializeField] private int _moveType;
private Vector3 _moveDirection;
private Vector3 _moveCurve;
In the Start function get a random number for the move type. Also call SetMoveDirection. This is a function that you will create next.
_moveType = Random.Range(0, 3);
SetMoveDirection();
Now create the SetMoveDirection function. This will be used in the Start function and in the CalculateMovement function whenever the enemy is reset to the top of the screen. Create a switch statement to handle the different movement types. For type 0 it will just move down. For type 1 it will move at an angle to the left or right depending on which side of the screen it starts. Type 2 is the same as type 1 but includes a Vector3 that will have it curve around the screen. Both type 1 and type 2 normalize their vectors so they move at a the normal speed.
void SetMoveDirection()
{
switch (_moveType)
{
case 0:
_moveDirection = Vector3.down;
break;
case 1:
if (transform.position.x > 0)
{
_moveDirection = Vector3.down + Vector3.left;
}
else
{
_moveDirection = Vector3.down + Vector3.right;
}
_moveDirection = _moveDirection.normalized;
break;
case 2:
if (transform.position.x > 0)
{
_moveDirection = Vector3.down + Vector3.left;
_moveCurve = new Vector3(0.003f, 0f, 0f);
}
else
{
_moveDirection = Vector3.down + Vector3.right;
_moveCurve = new Vector3(-0.003f, 0f, 0f);
}
_moveDirection = _moveDirection.normalized;
break;
default:
_moveDirection = Vector3.down;
break;
}
}
Last, you need to rework calculate movement by doing three things. First replace Vector3.down with your move direction variable. Add an if statement to so the type 2 will adjust the move direction with the move curve. Last, in the if statement for moving back to the top of the screen call the SetMoveDirection function so that it moves the correct way each time it comes down the screen.
void CalculateMovement()
{
transform.Translate(_moveDirection * _speed * Time.deltaTime);
if (_moveType == 2)
{
_moveDirection += _moveCurve;
_moveDirection = _moveDirection.normalized;
} if (transform.position.y < -5.0f)
{
float randomX = Random.Range(-8.0f, 8.0f);
transform.position = new Vector3(randomX, 7.0f, 0);
SetMoveDirection();
}
}
Now the enemies will have three different movement types, moving straight down, moving down at an angle, and moving down and curving around.
Good Luck Adventurer!
-Chris