Problem with flipping sprite.

So i’m having a problem with flipping my sprite, it works for one direction but not for the other. Maybe it’s just a stupid mistake but I just can’t find out what’s wrong.

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

public class enemyslimescript : MonoBehaviour
{
    Rigidbody rb;
    SpriteRenderer direction;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent <Rigidbody>();
        direction = GetComponent <SpriteRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        if (direction.flipX == true)
        {
            rb.velocity = new Vector3(-5, -1, 0);
        }
        if (direction.flipX == false)
        {
            rb.velocity = new Vector3(5, -1, 0);
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Obstacle")
        {
            if (direction.flipX == true)
            {
                direction.flipX = false;
            }
            if (direction.flipX == false)
            {
                direction.flipX = true;
            }
        }
    }
}

Please use code-tags when posting code. Don’t post plain-text as it’s very difficult to read. You can also edit your post to include this too.

Really, this is just a case of you not following your own code logically. Step through it in a debugger or just follow it with your mind: You check if flipX is true and if so then set it to false and then immediately after you check if it’s false and set it to true. In other words, you flip it twice from true → false → true again.

1 Like

Note you can simply do this:

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Obstacle")
    {
        direction.flipX = !direction.flipX;
    }
}