Unity movement help

Hello to this forum!

I am wondering about an aspect of my game and would like to hear different opinions. My game is quite simple, enemies spawn and walk from the right of the screen to the left and the player has to avoid them.

public class Movement : MonoBehaviour
{
    private float speed = 2f;

    // Update is called once per frame
    void Update()
    {
        if(!GameController.Instance.IsGameOver())
        {
            transform.position -= new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);
        }

        //If rectangle is out of bounds add it to the pool.
        if (transform.position.x < -10)
        {
            rectanglesPool.Instance.AddToPool(gameObject);
        }
    }
}

How can I change the code so that the enemies can also move from left to right? and from top to bot, and from bot to top? I was thinking about setting a public int variable (range from 0-3) and then a switch statement. But maybe there is a better solution. Thanks

A switch statement along with an int or enum would work, sure…

How about something easier to extend (and possibly overkill for what you want)

movement code:

using UnityEngine;

public class Movement : MonoBehaviour
{
    private IMovementAlgorithm MovementAlgorithm;

    public void SetMovementAlgorithm(IMovementAlgorithm movementAlgorithm)
    {
        MovementAlgorithm = movementAlgorithm;
    }

    private void Update()
    {
        if (MovementAlgorithm != null)
        {
            MovementAlgorithm.DoMove(objectToMove: this.transform);
        }
    }
}

the interface

using UnityEngine;

public interface IMovementAlgorithm
{
    void DoMove(Transform objectToMove);
}

Now your movement algorithms can be whatever you want, like up, left etc

using UnityEngine;

public class UpMover : IMovementAlgorithm
{
    public void DoMove(Transform objectToMove)
    {
        //move up logic
    }
}
using UnityEngine;

public class LeftMover : IMovementAlgorithm
{
    public void DoMove(Transform objectToMove)
    {
        //move left logic
    }
}

The advantage is you could add more complex movements

using UnityEngine;

public class ZigZagMover : IMovementAlgorithm
{
    public void DoMove(Transform objectToMove)
    {
        //move zigzag logic
    }
}
using UnityEngine;

public class SpiralMover : IMovementAlgorithm
{
    public void DoMove(Transform objectToMove)
    {
        //move spiral logic
    }
}

Just a thought. It might be overkill for what you want, but if you’re planning on having more complicated behaviour, this approach allows you to add as many move algorithms as you want and switch them at runtime.

Thank you, I will try it