Production: Wave Movement


Introduction

In the last post we added the ability for enemies to randomly follow the player. In this post, we’ll add another enemy type that will move horizontally across the screen in a wave moment.

The Challenge

The challenge is to create a new enemy type and have it start on the left or right of the screen to go across in a wave pattern.

Horizontal Enemy

First, I’ll make a copy of the enemy prefab and unpact it completely. I’ll remove the enemy script and update the sprite.
prefab

I’ll create a new script for this new enemy type. I’d like the speed to be random, and let a designer decide on the minimum and maximum range.

Let’s define and initialize a few fields.

[SerializeField] private float _minimumSpeed = 8.0f;
[SerializeField] private float _maximumSpeed = 12.0f;
private void Awake()
{
    _spriteRenderer = GetComponent<SpriteRenderer>();
    _speed = Random.Range(_minimumSpeed, _maximumSpeed);

    SetMoveDirection();
    SetStartingPosition();
}

Next we’ll create the wave movement pattern using Mathf.Sin along with two multiplier fields to adjust the wave height and frequency.

private void CalculateWaveMovement()
{
    transform.Translate(_speed * Time.deltaTime * Vector2.right, Space.World);

    currentPosition = transform.position;
    newPosition.x = currentPosition.x;
    newPosition.y = WAVE_HEIGHT * Mathf.Sin(currentPosition.x * WAVE_FREQUENCY);
    transform.position = newPosition;
}

To set the initial movement direction, I’ll set the _speed field to a positive or negative value, based on the random speed that was generated in the Awake method.

private void SetMoveDirection()
{
    _speed = _speed < (_minimumSpeed + _maximumSpeed) / 2.0 ? -(_speed) : _speed;
}

Then we’ll set the starting position basedon the move direction.

private void SetStartingPosition()
{
    var startingXPosition = Mathf.Sign(_speed) == -1 ? 10 : -10;
    transform.position = new Vector2(startingXPosition, transform.position.y);
    _spriteRenderer.flipX = startingXPosition > 0;
}

This enemy will be used as an obstacle for the player to avoid, so we don’t need to do anything else.
result

Summary

This is the basics of how our enemy wave spawn manager works. You can take the basics and add anything you need, like UI and music changes.

Stay tuned for the next post.
Take care.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s