Left and right enemy moving in 2D platformer

Good day!

I am working on a script for an enemy in a platformer game.I want it to move a specific distance left or right and then return to the origin and just to do the same thing.
please show me a way to script this thing.I already tried but can’t figure out the conditions.(In my script I used 2 bool movingRight and movingLeft).

Thank you very much!

There’s loads of ways of doing something like that. A simple way would be to have 2 variables that define the minimum X position of the enemy and the maximum X position. You could also have an integer that is -1 when moving left and +1 when moving right.

e.g.

float fMinX = 50.0f;
float fMaxX = 250.0f;
int Direction = -1;

Update:

switch( Direction )
{
    case -1:
        // Moving Left
        if( fEnemyX > fMinX )
        {
            fEnemyX -= 1.0f;
        }
        else
        {
            // Hit left boundary, change direction
            Direction = 1;
        }
        break;
      
    case 1:
        // Moving Right
        if( fEnemyX < fMaxX )
        {
            fEnemyX += 1.0f;
        }
        else
        {
            // Hit right boundary, change direction
            Direction = -1;
        }
        break;
}

sprEnemy.transform.localPosition = new Vector3( fEnemyX , 0.0f , 0.0f );
2 Likes

Thank you very much sir!

You saved my day! I really appreciate your help.Here is my final code:

// Use this for initialization
    void Start ()
    {
        initialPosition = transform.position;
        direction = -1;
        maxDist += transform.position.x;
        minDist -= transform.position.x;
    }
   
    // Update is called once per frame
    void Update ()
    {
        switch (direction)
        {
             case -1:
                // Moving Left
                if( transform.position.x > minDist)
                    {
                       GetComponent <Rigidbody2D>().velocity = new Vector2(-movingSpeed,GetComponent<Rigidbody2D>().velocity.y);
                    }
                else
                    {
                       direction = 1;
                    }
                break;
             case 1:
                  //Moving Right
                if(transform.position.x < maxDist)
                    {
                        GetComponent <Rigidbody2D>().velocity = new Vector2(movingSpeed,GetComponent<Rigidbody2D>().velocity.y);
                    }
                else
                    {
                        direction = -1;
                    }
            break;
        }
    }

}

Have a nice day!

No problem, glad you got it working ok