A different solution to moving the formation

I just thought I’d share my solution to moving the enemy formation around since it ended up being different from the method used in the lesson. I did all the same stuff to set the X min and max values, and also included a public float for the speed. The part where my code differed was that I also declared a float called “direction” and set it to 1. I put all my code in a function called MoveFormation to keep my Update function tidy. This is what it looked like before I watched the rest of the video:

    void MoveFormation()
{
    if (transform.position.x <= xMin)
    {
        direction = direction * -1;
    } 

    if ( transform.position.x >= xMax)
    {
        direction = direction * -1;
    }

    transform.position += Vector3.left * enemySpeed * Time.deltaTime * direction;

    float newX = Mathf.Clamp(transform.position.x, xMin, xMax);
    transform.position = new Vector3(newX, transform.position.y, transform.position.z);
}

So basically, the formation is always being moved by Vector3.left, but when it hits the left edge of the screen it begins moving “negative left” (aka right) since the direction is now -1. The direction is also flipped when it hits the right edge.

I had a hunch that there was a more elegant way to write my if statements, and after learning about the “||” thing in the video, I merged them into one statement. Great course so far!

2 Likes

In fact you don’t even need the direction variable - you can directly change the speed variable, like this:
enemySpeed = -enemySpeed;

Privacy & Terms