Enemy Flip Glitch

I tried to make an enemy script which is first patrol and if enemy saw a player, it will fire and again if player was far away it follows the player and again attacks bandicam 2021-09-06 21-27-09-392.avi - Google Drive
And this is the glich occurs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAi : MonoBehaviour
{
    //Enemy's Ground Detection
    public float rayDistance;
    private bool movingRight = false;
    public float speed;
    public Transform groundDetection;

    //Enemy's view Initializations and Attack Initialization
    public Transform sight;
    public float sov;

    //Firing Initializations
    public Transform firePoint;      
    public Transform player;
    public float attackDistance;
    private bool isAttack;
    public GameObject bulletSprite;

    //Player Physics;
    public Rigidbody2D rb;

    //private bool isRight = false;

    private float timeBtwShots;
    public float startTimeBtwShots;

    private bool facingRight = true;
   
    // Start is called before the first frame update
    void Start()
    {
        //Flip(true);
        //player = GameObject.FindGameObjectWithTag("Player").transform;
        isAttack = false;

        timeBtwShots = startTimeBtwShots;

    }

    // Update is called once per frame
    void Update()
    {
        //On stage Patrol wait until player spots
        if (isAttack == false)
        {
            Patrol();

            RaycastHit2D hitInfo = Physics2D.Raycast(sight.position, sight.right, sov);
            if (hitInfo.collider == true)
            {
                if (hitInfo.collider.gameObject.CompareTag("Player") == true)
                {
                    Debug.Log("Found Player");
                    isAttack = true;
                }
            }
        }
        else
        {
            Fire();  
        }
        //Player Spotted
       

    }

    void Patrol()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
        RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, rayDistance);
        if (groundInfo.collider == false)
        {
            if (movingRight == false)
            {
                Flip(true);
                //transform.eulerAngles = new Vector3(0, -180, 0);
                movingRight = true;
            }
            else
            {
                Flip(false);
                //transform.eulerAngles = new Vector3(0, 0, 0);
                movingRight = false;
            }
        }

    }

    void Fire()
    {
        //Debug.Log("Attack!");
        //Enemy Start to Shoot;
        if (timeBtwShots <= 0)
        {
            Instantiate(bulletSprite, firePoint.position, firePoint.rotation);
            timeBtwShots = startTimeBtwShots;
        }
        else
        {
            timeBtwShots -= Time.deltaTime;
        }

        float isFollowDistance = Vector2.Distance(transform.position, player.position);
        if(isFollowDistance > 6)
        {
            Follow();
        }

        if (player.transform.position.x >= transform.position.x) {
            if(!facingRight) Flip(false);
        }
        else if(facingRight) Flip(true);
       
        //float xDist = player.position.x - transform.position.x;
        //if(rb.velocity.x >= 1)
        //{
            //Flip(true);
        //}
        //else if(rb.velocity.x <= -0.01)
        //{
            //Flip(false);
        //}
    
    }

    void Follow()
    {
        Debug.Log("Follow Player");
        if(transform.position.x < player.position.x)
        {
            rb.velocity = new Vector2(3, 0);
            //Flip(true);
            //transform.Rotate(0f, 180f, 0f);
        }

        else if(transform.position.x > player.position.x)
        {
            rb.velocity = new Vector2(-3, 0);
            //Flip(false);
            //transform.Rotate(0f, 0f, 0f);
        }
    }

    void Flip(bool isRight)
    {
        if(isRight == true)
        {
            transform.Rotate(0f, -180f, 0f);
        }
        else if(isRight == false)
        {
            transform.Rotate(0f, 0f, 0f);
        }
    }
}

This is the whole code pls anyone can help with this.
The enemy had weapons too.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

1 Like

hey i dont know if this will help but i think thoses lines of codes are runing in the update function, so that’s why it’s glitching when it flip ,
for your case you should maybe use transform.rotation = new Quaternion (0f,0f,90f,0f); instead of transform.Rotate(0f, -180f, 0f);
and i saw u used transform.Rotate(0f, -0f, 0f); too down below wich is completely useless
i think u really wanted to use transform.rotation = new Quaternion (0f,0f,90f,0f) instead of transform.Rotate
good luck for your game

1 Like

Thanks fr the answer I’ll try it. But I have another question, does this code is right?

Looking at code and deciding it is right is actually NOT a thing.

Follow the steps above to run it and find out what it is DOING.

1 Like