enemy AI patrol not working

I made this code for my enemy but it just flickers side to side, anyone know what i could do ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonsterAi : MonoBehaviour
{

public float speed;

private bool movingRight = true;

public Transform groundDetection;

// Use this for initialization
void Update()
{
    transform.Translate(Vector2.right * speed * Time.deltaTime);

    RaycastHit2D groundinfo = Physics2D.Raycast(groundDetection.position, Vector2.down, 2f);
    if (groundinfo.collider == false)
    {
        if (movingRight == true)
        {
            transform.eulerAngles = new Vector3(0, -180, 0);
            movingRight = false;
        } else {
            transform.eulerAngles = new Vector3(0, 0, 0);
            movingRight = true;
        }
        
    }
}

}

Hi!

Well, it flickers side to side because one frame your scripts detects that “movingRight == true” and set up it to false immediately, so the next frame detects that “movingRight == false” or “else” in your script and it set up it to true and so go on.
You should set up a logic for your if(movingRight == true) and else so it won’t be switched just because it’s true or false, otherwise it will flick, because there is no other logic in that check statement.

Also that means that your groudinfo.collider consistently false.


Also, would like to comment your Translate function just in case:

transform.Translate(Vector2.right * speed * Time.deltaTime);

The thing is that you are always moving your enemy to the right, because you are using Vector2.right variable that is static and independent of your transform orientation.
If that is intentionally then ok, but if you wanted it to move accordingly to your transform orientation then you should use transform.right, because it will take into consideration your character orientation and move to appropriate facing direction.


Hope that helps.