Enemy Movement Types

Create multiple movement scripts and combine them

Tristan Engel
2 min readJul 16, 2021

A few articles before we decided to split the enemy behavior script in multiple smaller script that can be combined to create new enemy types. This partly prevent having to write the same code for each new enemy variation we create.

In this article we create 3 additional movement behavior scripts.

1. Left or Right movement
2. Zig Zag type movement
3. Circular movement

Left or Right movement Script

We already have a script to move straight down. By combining the Left/Right movement script we can make our enemy move diagonally.

[SerializeField] private float _speed = 2f;
// Start is called before the first frame update
void Start()
{
if (Random.value > 0.5f)
{
_speed *= -1;
}
}

// Update is called once per frame
void Update()
{
transform.Translate(Vector3.right * _speed * Time.deltaTime);
}

Zig Zag type movement Script

The Zig Zag script is to be used along with the moving straight down script. The Zig Zag script moves the object from left to right endlessly. Together they result in a Zig Zag pattern.
A coroutine is used to switch between going left and right.

[SerializeField] private float _speed = 2f;
[SerializeField] private float _switchTime = 1f;

// Start is called before the first frame update
void Start()
{
if (Random.value > 0.5f)
{
_speed *= -1;
}
StartCoroutine(ZigZagSwitch());
}

// Update is called once per frame
void Update()
{
transform.Translate(Vector3.right * _speed * Time.deltaTime);
}

IEnumerator ZigZagSwitch()
{
while (true)
{
_speed *= -1;
yield return new WaitForSeconds(_switchTime);
}
}

Circular movement Script

Finally we got the circular movement script. This sets a random point around which the object moves in a circle.

private float _angle = 90f; //set to 90 so it starts at the top of the circle
[SerializeField] private float _speed = 0.5f;
[SerializeField] private float _radius = 5f;
[SerializeField] private float _centerPosX, _centerPosY;
private float _x, _y;

// Start is called before the first frame update
void Start()
{
_centerPosX = Random.Range(-8f, 8f);
_centerPosY = Random.Range(5f, 9f);
_radius = Random.Range(5f, 12f);
_speed = Random.Range(0.5f, 1f);
if (Random.value > 0.5f)
{
_speed *= -1;
}
}

// Update is called once per frame
void Update()
{
_angle += _speed * Time.deltaTime;
_x = Mathf.Cos(_angle) * _radius + _centerPosX;
_y = Mathf.Sin(_angle) * _radius + _centerPosY;
transform.position = new Vector3(_x, _y, 0);
}

--

--

Tristan Engel
Tristan Engel

Written by Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

No responses yet