No need to fix the formation movement

I don’t check for the edges, but define the allowed range of the center position. Even works at speed 200 :slight_smile:

Here’s my EnemyFormation.cs

The width of the formation is a given, so the left and right max values for the formation center are available. When the center reaches the allowed edge, the direction can immediately be changed.

I clamped exactly like we did with the player. And when we’ re at either maximum bound I simply inverse the speed. No need for a bool or more than one If.

I agree, it seems better to do it this way!

Never found this one, i clamped the enemy just in case… and for my sake i didn’t found this bug.
If you remove the clamp section, the issue is back.

void Update () {
        if (sideReached)
            transform.position += Vector3.left * speed * Time.deltaTime;
            transform.position += Vector3.right * speed * Time.deltaTime;

    //Better to join an if and avoid else
    if (transform.position.x <= xmin || transform.position.x >= xmax)
        sideReached = !sideReached;

    //Player movement restriction to gamespace
    //Issue with boundary: implementing clamp avoids this issue, transform
    //could not reach out boundary
    float newX = Mathf.Clamp(transform.position.x, xmin, xmax);
    transform.position = new Vector3(newX, transform.position.y, transform.position.z);
1 Like

Mate couldn’t agree more with the clamp thing. I often wondered while watching the video why Math.clamp wasn’t being used in the code. Perhaps he wanted us to see another way to sort it out. Anyway, I’ll try to figure out how to implement this function in my code.


Excellent! Thanks! This works way better than the code given on the video!

I think the reason he didn’t use Mathf.Clamp was that, rather than constraining the origin, he was checking the edges. This meant he needed to do two checks, one with the left edge of the formation, and one with the right edge. Like I think most of the others here, I created a minX and maxX based on the screen width +/- the formation width / 2, then clamped the origin within those two points. I still had to use If statements to see if the formation was at the edge, and if it was at the left edge, set moveRight to true, and if it was at the right edge, set moveRight to false.

Privacy & Terms