Forum begins after the advertisement:


[Part 11] Struggles with UI and Player Flip()

Home › Forums › Video Game Tutorial Series › Creating a Metroidvania in Unity › [Part 11] Struggles with UI and Player Flip()

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #20159
    Nirvik Rajbhandari
    Level 8
    Participant
    Helpful?
    Up
    0
    ::

    After finishing part 11 of the Creating A Metroidvania series, the pause menu UI was visible when pausing the game. Additionally, after wall jumping the player’s sprite flips and then wont flip back to its proper orientation in stead being in reverse of what is should be. Link to Github. https://github.com/KingPloof393/Metroidvania-Prototype

    #20162
    Chelsea
    Level 5
    Moderator
    Helpful?
    Up
    0
    ::

    Hi! For the sprite flipping issue, you could try sharing the relevant scripts along with a description of the problem for our AI reply bot to help fix. It should be able to help identify what’s causing the issue and suggest a possible fix.

    I’ve attached the following scripts from your project that may be relevant to the issues

    PlayerController.cs

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UIElements;
    using UnityEngine.UI;
    
    public class PlayerController : MonoBehaviour
    {
        [Header("Horizontal Movement Settings:")]
        [SerializeField] private float walkSpeed = 1; //sets the players movement speed on the ground
        [Space(5)]
    
        [Header("Vertical Movement Settings")]
        [SerializeField] private float jumpForce = 45f; //sets how hight the player can jump
    
        private float jumpBufferCounter = 0; //stores the jump button input
        [SerializeField] private float jumpBufferTime; //sets the max amount of frames the jump buffer input is stored
    
        private float coyoteTimeCounter = 0; //stores the Grounded() bool
        [SerializeField] private float coyoteTime; //sets the max amount of frames the Grounded() bool is stored
    
        private int airJumpCounter = 0; //keeps track of how many times the player has jumped in the air
        [SerializeField] private int maxAirJumps; //the max no. of air jumps
    
        [SerializeField] private int maxFallingSpeed; //max fall speed
    
        private float gravity; //stores the gravity scale at start
        [Space(5)]
    
        [Header("Wall Jump Settings")]
        [SerializeField] private float wallSlidingSpeed;
        [SerializeField] private Transform wallCheck;
        [SerializeField] private LayerMask wallLayer;
        [SerializeField] private float wallJumpingDuration;
        [SerializeField] private Vector2 wallJumpingPower;
        float wallJumpingDirection;
        bool isWallSliding;
        bool isWallJumping;
        [Space(5)]
    
    
        [Header("Ground Check Settings:")]
        [SerializeField] private Transform groundCheckPoint; //point at which ground check happens
        [SerializeField] private float groundCheckY = 0.2f; //how far down from ground chekc point is Grounded() checked
        [SerializeField] private float groundCheckX = 0.5f; //how far horizontally from ground chekc point to the edge of the player is
        [SerializeField] private LayerMask whatIsGround; //sets the ground layer
        bool isGrounded;
    
        [Space(5)]
    
        [Header("Dash Settings")]
        [SerializeField] private float dashSpeed; //speed of the dash
        [SerializeField] private float dashTime; //amount of time spent dashing
        [SerializeField] private float dashCooldown; //amount of time between dashes
        [SerializeField] GameObject dashEffect;
        private bool canDash = true, dashed;
        [Space(5)]
    
        [Header("Attack Settings:")]
        [SerializeField] private Transform SideAttackTransform; //the middle of the side attack area
        [SerializeField] private Vector2 SideAttackArea; //how large the area of side attack is
    
        [SerializeField] private Transform UpAttackTransform; //the middle of the up attack area
        [SerializeField] private Vector2 UpAttackArea; //how large the area of side attack is
    
        [SerializeField] private Transform DownAttackTransform; //the middle of the down attack area
        [SerializeField] private Vector2 DownAttackArea; //how large the area of down attack is
    
        [SerializeField] private LayerMask attackableLayer; //the layer the player can attack and recoil off of
    
        [SerializeField] private float timeBetweenAttack;
        private float timeSinceAttack;
    
        [SerializeField] private float damage; //the damage the player does to an enemy
    
        [SerializeField] private GameObject slashEffect; //the effect of the slashs
    
        bool restoreTime;
        float restoreTimeSpeed;
        [Space(5)]
    
        [Header("Recoil Settings:")]
        [SerializeField] private int recoilXSteps = 5; //how many FixedUpdates() the player recoils horizontally for
        [SerializeField] private int recoilYSteps = 5; //how many FixedUpdates() the player recoils vertically for
    
        [SerializeField] private float recoilXSpeed = 100; //the speed of horizontal recoil
        [SerializeField] private float recoilYSpeed = 100; //the speed of vertical recoil
    
        private int stepsXRecoiled, stepsYRecoiled; //the no. of steps recoiled horizontally and verticall
        [Space(5)]
    
        [Header("Health Settings")]
        public int health;
        public int maxHealth;
        public int maxTotalHealth = 10;
        public int heartShards;
        [SerializeField] GameObject bloodSpurt;
        [SerializeField] float hitFlashSpeed;
        public delegate void OnHealthChangedDelegate();
        [HideInInspector] public OnHealthChangedDelegate onHealthChangedCallback;
    
        float healTimer;
        [SerializeField] float timeToHeal;
        [Space(5)]
    
        [Header("Mana Settings")]
        [SerializeField] UnityEngine.UI.Image manaStorage;
        public bool halfMana;
        [SerializeField] float mana;
        [SerializeField] float manaDrainSpeed;
        [SerializeField] float manaGain;
    
        public ManaOrbsHandler manaOrbsHandler;
        public int orbShard;
        public int manaOrbs;
        [Space(5)]
    
        [Header("Spell Settings")]
        //spell stats
        [SerializeField] float manaSpellCost = 0.3f;
        [SerializeField] float timeBetweenCast = 0.5f;
        float timeSinceCast;
        [SerializeField] float spellDamage; //upspellexplosion and downspellfireball
        [SerializeField] float downSpellForce; // desolate dive only
        //spell cast objects
        [SerializeField] GameObject sideSpellFireball;
        [SerializeField] GameObject upSpellExplosion;
        [SerializeField]  GameObject downSpellFireball;
        float castOrHealTimer;
        [Space(5)]
    
        [Header("Camera Settings")]
        [SerializeField] private float playerFallSpeedThreshold = -10;
        [Space(5)]
    
        [Header("Audio")]
        [SerializeField] AudioClip landingSound;
        [SerializeField] AudioClip jumpSound;
        [SerializeField] AudioClip dashAndAttackSound;
        [SerializeField] AudioClip spellCastSound;
        [SerializeField] AudioClip hurtSound;
        private AudioSource audioSource;
    
        [HideInInspector] public PlayerStateList pState;
        private Animator anim;
        public Rigidbody2D rb;
        private SpriteRenderer sr;
    
        //Input Variables
        private float xAxis, yAxis;
        private bool attack = false;
        bool openMap;
        bool openInventory;
    
        bool landingSoundPlayed;
    
        private bool canFlash = true;
    
        //creates a singleton of the PlayerController
        public static PlayerController Instance;
    
        //unlocking
        public bool unlockedWallJump;
        public bool unlockedDash;
        public bool unlockedSideSpell;
        public bool unlockedUpSpell;
        public bool unlockedDownSpell;
        public bool unlockedDoubleJump;
    
        private void Awake()
        {
            if (Instance != null && Instance != this)
            {
                Destroy(gameObject);
            }
            else
            {
                Instance = this;
            }
            DontDestroyOnLoad(gameObject);
        }
    
    
        // Start is called before the first frame update
        void Start()
        {
            pState = GetComponent<PlayerStateList>();
    
            rb = GetComponent<Rigidbody2D>();
            sr = GetComponent<SpriteRenderer>();
            audioSource = GetComponent<AudioSource>();
    
            anim = GetComponent<Animator>();
            manaOrbsHandler = FindObjectOfType<ManaOrbsHandler>();
    
            Health = maxHealth;
    
            Mana = mana;
            manaStorage.fillAmount = Mana;
            SaveData.Instance.StartPlayerData();
            SaveData.Instance.LoadPlayerData();
    
            FindObjectOfType<HeartController>().InstantiateHeartContainers();
    
            if (halfMana)
            {
                CutMana();
            }
            else
            {
                RestoreMana();
            }
    
            gravity = rb.gravityScale;
    
            if (Health == 0)
            {
                pState.alive = false;
                GameManager.Instance.RespawnPlayer();
            }
        }
    
        private void OnDrawGizmos()
        {
            Gizmos.color = Color.red;
            Gizmos.DrawWireCube(SideAttackTransform.position, SideAttackArea);
            Gizmos.DrawWireCube(UpAttackTransform.position, UpAttackArea);
            Gizmos.DrawWireCube(DownAttackTransform.position, DownAttackArea);
        }
    
        // Update is called once per frame
        void Update()
        {
            if(GameManager.Instance.gameIsPaused) return;
            isGrounded = Grounded();
            if (pState.cutscene) return;
            if (pState.alive)
            {
                GetInputs();
                ToggleMap();
                ToggleInventory();
            }
            UpdateJumpVariables();
            RestoreTimeScale();
            UpdateCameraYDampForPlayerFall();
    
            if (pState.alive)
            {
                if (!(Time.timeScale == 0))
                {
                    if (pState.dashing) return;
                    Heal();
                    CastSpell();
                    if (pState.healing) return;
                    if (!isWallJumping)
                    {
                        Flip();
                        Move();
                        Jump();
                    }
                    if (unlockedWallJump)
                    {
                        WallSlide();
                        WallJump();
                    }
                    if (unlockedDash)
                    {
                        StartDash();
                    }
                    Attack();
                    FlashWhileInvincible();
                }
            }
    
        }
        private void OnTriggerEnter2D(Collider2D _other) //for up and down cast spell
        {
            if(_other.GetComponent<Enemy>() != null && pState.casting)
            {
                _other.GetComponent<Enemy>().EnemyGetsHit(spellDamage, (_other.transform.position - transform.position).normalized, -recoilYSpeed);
            }
        }
    
        private void FixedUpdate()
        {
            if (pState.dashing || pState.healing || pState.cutscene) return;
            Recoil();
        }
    
        void GetInputs()
        {
            xAxis = Input.GetAxisRaw("Horizontal");
            yAxis = Input.GetAxisRaw("Vertical");
            attack = Input.GetButtonDown("Attack");
            openMap = Input.GetButton("Map");
            openInventory = Input.GetButton("Inventory");
    
            if (Input.GetButton("Cast/Heal"))
            {
                castOrHealTimer += Time.deltaTime;
            }
        }
    
        void ToggleMap()
        {
            if(openMap)
            {
                UIManager.Instance.mapHandler.SetActive(true);
            }
            else
            {
                UIManager.Instance.mapHandler.SetActive(false);
            }
        }
    
        void ToggleInventory()
        {
            if (openInventory)
            {
                UIManager.Instance.inventory.SetActive(true);
            }
            else
            {
                UIManager.Instance.inventory.SetActive(false);
            }
        }
    
        void Flip()
        {
            if (xAxis > 0 && !pState.lookingRight)
            {
                Turn();
            }
            else if (xAxis < 0 && pState.lookingRight)
            {
                Turn();
            }
        }
    
        void Turn()
        {
            pState.lookingRight = !pState.lookingRight;
            float yRotation = pState.lookingRight ? 0 : 180;
            transform.eulerAngles = new Vector3(0, yRotation, 0);
        }
    
        private void Move()
        {
            if (pState.healing)
            {
                rb.velocity = new Vector2(0, 0);
                return;
            }
            rb.velocity = new Vector2(walkSpeed * xAxis, rb.velocity.y);
            anim.SetBool("Walking", rb.velocity.x != 0 && isGrounded);
        }
    
        void UpdateCameraYDampForPlayerFall()
        {
            if(rb.velocity.y < playerFallSpeedThreshold && !CameraManager.Instance.isLerpingYDamping && !CameraManager.Instance.hasLerpedYDamping)
            {
                StartCoroutine(CameraManager.Instance.LerpYDamping(true));
            }
    
            if (rb.velocity.y >= 0 && !CameraManager.Instance.isLerpingYDamping && CameraManager.Instance.hasLerpedYDamping)
            {
                CameraManager.Instance.hasLerpedYDamping = false;
                StartCoroutine(CameraManager.Instance.LerpYDamping(false));
            }
        }
    
        void StartDash()
        {
            if (Input.GetButtonDown("Dash") && canDash && !dashed)
            {
                StartCoroutine(Dash());
                dashed = true;
            }
    
            if (isGrounded)
            {
                dashed = false;
            }
        }
    
        IEnumerator Dash()
        {
            canDash = false;
            pState.dashing = true;
            anim.SetTrigger("Dashing");
            audioSource.PlayOneShot(dashAndAttackSound);
            rb.constraints |= RigidbodyConstraints2D.FreezePositionY;
            int _dir = pState.lookingRight ? 1 : -1;
            rb.velocity = new Vector2(_dir * dashSpeed, 0);
            if (isGrounded) Instantiate(dashEffect, transform);
            yield return new WaitForSeconds(dashTime);
            rb.constraints &= ~RigidbodyConstraints2D.FreezePositionY;
            pState.dashing = false;
            yield return new WaitForSeconds(dashCooldown);
            canDash = true;
        }
    
        public IEnumerator WalkIntoNewScene(Vector2 _exitDir, float Delay)
        {
            if(_exitDir.y > 0)
            {
                rb.velocity = jumpForce * _exitDir;
            }
    
            if(_exitDir.x != 0)
            {
                Flip();
                if (pState == null) 
                { 
                    yield break; 
                } 
                pState.invincible = true;
                xAxis = _exitDir.x > 0 ? 1 : -1;
                Move();
                anim.SetBool("Walking", true);
                Flip();
            }
            yield return new WaitForSeconds(Delay);
            pState.invincible = false;
            pState.cutscene = false;
        }
    
        void Attack()
        {
            timeSinceAttack += Time.deltaTime;
            if (attack && timeSinceAttack >= timeBetweenAttack)
            {
                timeSinceAttack = 0;
                anim.SetTrigger("Attacking");
                audioSource.PlayOneShot(dashAndAttackSound);
    
                if (yAxis == 0 || yAxis < 0 && isGrounded)
                {
                    int _recoilLeftOrRight = pState.lookingRight ? 1 : -1;
    
                    Hit(SideAttackTransform, SideAttackArea, ref pState.recoilingX, Vector2.right * _recoilLeftOrRight, recoilXSpeed);
                    Instantiate(slashEffect, SideAttackTransform);
                }
                else if (yAxis > 0)
                {
                    Hit(UpAttackTransform, UpAttackArea, ref pState.recoilingY, Vector2.up, recoilYSpeed);
                    SlashEffectAtAngle(slashEffect, 80, UpAttackTransform);
                }
                else if (yAxis < 0 && !isGrounded)
                {
                    Hit(DownAttackTransform, DownAttackArea, ref pState.recoilingY, Vector2.down, recoilYSpeed);
                    SlashEffectAtAngle(slashEffect, -90, DownAttackTransform);
                }
            }
    
    
        }
        void Hit(Transform _attackTransform, Vector2 _attackArea, ref bool _recoilBool, Vector2 _recoilDir, float _recoilStrength)
        {
            Collider2D[] objectsToHit = Physics2D.OverlapBoxAll(_attackTransform.position, _attackArea, 0, attackableLayer);
            List<Enemy> hitEnemies = new List<Enemy>();
    
             if(objectsToHit.Length > 0)
            {
                _recoilBool = true;
            } 
            for(int i = 0; i < objectsToHit.Length; i++)
            {
                Enemy e = objectsToHit[i].GetComponent<Enemy>();
                if(e && !hitEnemies.Contains(e))
                {
                    e.EnemyGetsHit(damage, _recoilDir, _recoilStrength);
                    hitEnemies.Add(e);
    
                    if (objectsToHit[i].CompareTag("Enemy"))
                    {
                        if(Mana < (halfMana ? 0.5f : 1f))
                        {
                            Mana += manaGain;
                        }
                        else
                        {
                            manaOrbsHandler.UpdateMana(manaGain * 3f);
                        }
                    }
                }
            }
        }
        void SlashEffectAtAngle(GameObject _slashEffect, int _effectAngle, Transform _attackTransform)
        {
            _slashEffect = Instantiate(_slashEffect, _attackTransform);
            _slashEffect.transform.eulerAngles = new Vector3(0, 0, _effectAngle);
            _slashEffect.transform.localScale = new Vector2(transform.localScale.x, transform.localScale.y);
        }
        void Recoil()
        {
            if (pState.recoilingX)
            {
                if (pState.lookingRight)
                {
                    rb.velocity = new Vector2(-recoilXSpeed, 0);
                }
                else
                {
                    rb.velocity = new Vector2(recoilXSpeed, 0);
                }
            }
    
            if (pState.recoilingY)
            {
                rb.gravityScale = 0;
                if (yAxis < 0)
                {
                    rb.velocity = new Vector2(rb.velocity.x, recoilYSpeed);
                }
                else
                {
                    rb.velocity = new Vector2(rb.velocity.x, -recoilYSpeed);
                }
                airJumpCounter = 0;
            }
            else
            {
                rb.gravityScale = gravity;
            }
    
            //stop recoil
            if (pState.recoilingX && stepsXRecoiled < recoilXSteps)
            {
                stepsXRecoiled++;
            }
            else
            {
                StopRecoilX();
            }
            if (pState.recoilingY && stepsYRecoiled < recoilYSteps)
            {
                stepsYRecoiled++;
            }
            else
            {
                StopRecoilY();
            }
    
            if (isGrounded)
            {
                StopRecoilY();
            }
        }
        void StopRecoilX()
        {
            stepsXRecoiled = 0;
            pState.recoilingX = false;
        }
        void StopRecoilY()
        {
            stepsYRecoiled = 0;
            pState.recoilingY = false;
        }
        public void TakeDamage(float _damage)
        {
            if (pState.alive)
            {
                audioSource.PlayOneShot(hurtSound);
    
                if (pState.invincible) return;
                Health -= Mathf.RoundToInt(_damage);
                if (Health <= 0)
                {
                    Health = 0;
                    StartCoroutine(Death());
                }
                else
                {
                    StartCoroutine(StopTakingDamage());
                }
            }
        }
        IEnumerator StopTakingDamage()
        {   
            pState.invincible = true;
            GameObject _bloodSpurtParticles = Instantiate(bloodSpurt, transform.position, Quaternion.identity);
            Destroy(_bloodSpurtParticles, 1.5f);
            anim.SetTrigger("TakeDamage");
            yield return new WaitForSeconds(1f);
            pState.invincible = false;
        }
        IEnumerator Flash()
        {
            sr.enabled = !sr.enabled;
            canFlash = false;
            sr.material.color = pState.invincible ? Color.Lerp(Color.white, Color.black, Mathf.PingPong(Time.time * hitFlashSpeed, 1.0f)) : Color.white;
            yield return new WaitForSeconds(0.2f);
            sr.material.color = Color.white;
            canFlash = true;
        }
        void FlashWhileInvincible()
        {
            if(pState.invincible && !pState.cutscene)
            {
                if(Time.timeScale > 0.1 && canFlash)
                {
                    StartCoroutine(Flash());
                }
            }
        }
        void RestoreTimeScale()
        {
            if (restoreTime)
            {
                if (Time.timeScale < 1)
                {
                    Time.timeScale += Time.unscaledDeltaTime * restoreTimeSpeed;
                }
                else
                {
                    Time.timeScale = 1;
                    restoreTime = false;
                }
            }
            else
            {
                sr.enabled = true;
            }
        }
    
        IEnumerator StartTimeAgain(float _delay)
        {
            yield return new WaitForSecondsRealtime(_delay);
            restoreTime = true;
        }
    
        IEnumerator Death()
        {
            pState.alive = false;
            rb.constraints = RigidbodyConstraints2D.FreezePositionX; 
            Time.timeScale = 1f;
            GameObject _bloodSpurtParticles = Instantiate(bloodSpurt, transform.position, Quaternion.identity);
            Destroy(_bloodSpurtParticles, 1.5f);
            anim.SetTrigger("Death");
            rb.constraints = RigidbodyConstraints2D.FreezePosition;
    
            yield return new WaitForSeconds(0.9f);
            StartCoroutine(UIManager.Instance.ActivateDeathScreen());
    
            yield return new WaitForSeconds(0.9f);
            if(Shade.Instance != null)
            {
                Destroy(Shade.Instance.gameObject);
            }
            SaveData.Instance.ClearShadeData();
            Instantiate(GameManager.Instance.shade, transform.position, Quaternion.identity);
        }
    
        public void Respawn()
        {
            rb.constraints = RigidbodyConstraints2D.None;
            rb.constraints = RigidbodyConstraints2D.FreezeRotation;
            if (!pState.alive)
            {
                pState.alive = true;
                CutMana();
                Mana = 0;
                manaOrbsHandler.orbFills[0].fillAmount = 0;
                manaOrbsHandler.orbFills[1].fillAmount = 0;
                manaOrbsHandler.orbFills[2].fillAmount = 0;
                Health = maxHealth;
                anim.Play("Player_Idle");
                SaveData.Instance.SavePlayerAbilitiesData();
            }
        }
    
        public void CutMana()
        {
            halfMana = true;
            UIManager.Instance.SwitchMana(UIManager.ManaState.HalfMana);
        }
    
        public void RestoreMana()
        {
            halfMana = false;
            UIManager.Instance.SwitchMana(UIManager.ManaState.FullMana);
            manaOrbsHandler.usedMana = true;
        }
    
        public void HitStopTime(float _newTimeScale, int _restoreSpeed, float _delay)
        {
            restoreTimeSpeed = _restoreSpeed;
            if (_delay > 0)
            {
                StopCoroutine(StartTimeAgain(_delay));
                StartCoroutine(StartTimeAgain(_delay));
            }
            else
            {
                restoreTime = true;
            }
            Time.timeScale = _newTimeScale;
        }
    
        public int Health
        {
            get { return health; }
            set
            {
                if (health != value)
                {
                    health = Mathf.Clamp(value, 0, maxHealth);
    
                    if (onHealthChangedCallback != null)
                    {
                        onHealthChangedCallback.Invoke();
                    }
                }
            }
        }
        void Heal()
        {
            if (Input.GetButton("Cast/Heal") && castOrHealTimer > 0.05f && Health < maxHealth && Mana > 0 && isGrounded && !pState.dashing && xAxis == 0)
            {
                pState.healing = true;
                anim.SetBool("Healing", true);
    
                //healing
                healTimer += Time.deltaTime;
                rb.velocity = Vector2.zero;
                if (healTimer >= timeToHeal)
                {
                    Health++;
                    healTimer = 0;
                }
    
                //drain mana
                manaOrbsHandler.usedMana = true;
                manaOrbsHandler.countDown = 3f;
                Mana -= Time.deltaTime * manaDrainSpeed;
            }
            else
            {
                pState.healing = false;
                anim.SetBool("Healing", false);
                healTimer = 0;
            }
        }
        public float Mana
        {
            get { return mana; }
            set
            {
                //if mana stats change
                if (mana != value)
                {
                    if (!halfMana)
                    {
                        mana = Mathf.Clamp(value, 0, 1);
                    }
                    else
                    {
                        mana = Mathf.Clamp(value, 0, 0.5f);
                    }
                    manaStorage.fillAmount = Mana;
                }
            }
        }
    
        void CastSpell()
        {
            if (Input.GetButtonUp("Cast/Heal") && castOrHealTimer <= 0.25f && timeSinceCast >= timeBetweenCast && Mana >= manaSpellCost)
            {
                pState.casting = true;
                timeSinceCast = 0;
                StartCoroutine(CastCoroutine());
            }
            else
            {
                timeSinceCast += Time.deltaTime;
            }
    
            if(!Input.GetButton("Cast/Heal"))
            {
                castOrHealTimer = 0;
            }
    
            if(isGrounded)
            {
                CancelDownSpell();
            }
            //if down spell is active, force player down until grounded
            if(downSpellFireball.activeInHierarchy)
            {
                rb.velocity += downSpellForce * Vector2.down;
            }
        }
    
        public void CancelDownSpell()
        {
            downSpellFireball.SetActive(false);
        }
        IEnumerator CastCoroutine()
        {
    
    
            //side cast
            if ((yAxis == 0 || (yAxis < 0 && isGrounded)) && unlockedSideSpell)
            {
                anim.SetBool("Casting", true);
                audioSource.PlayOneShot(spellCastSound);
                yield return new WaitForSeconds(0.15f);
                GameObject _fireBall = Instantiate(sideSpellFireball, SideAttackTransform.position, Quaternion.identity);
    
                //flip fireball
                if(pState.lookingRight)
                {
                    _fireBall.transform.eulerAngles = Vector3.zero; // if facing right, fireball continues as per normal
                }
                else
                {
                    _fireBall.transform.eulerAngles = new Vector2(_fireBall.transform.eulerAngles.x, 180); 
                    //if not facing right, rotate the fireball 180 deg
                }
                pState.recoilingX = true;
                Mana -= manaSpellCost;
                manaOrbsHandler.usedMana = true;
                manaOrbsHandler.countDown = 3f;
                yield return new WaitForSeconds(0.35f);
            }
    
            //up cast
            else if(yAxis > 0 && unlockedUpSpell)
            {
                anim.SetBool("Casting", true);
                audioSource.PlayOneShot(spellCastSound);
                yield return new WaitForSeconds(0.15f);
                Vector2 upSpellPosition = new Vector2(transform.position.x, transform.position.y + 1);
                Instantiate(upSpellExplosion, upSpellPosition, Quaternion.identity);
                rb.velocity = Vector2.zero;
                Mana -= manaSpellCost;
                manaOrbsHandler.usedMana = true;
                manaOrbsHandler.countDown = 3f;
                yield return new WaitForSeconds(0.35f);
            }
    
            //down cast
            else if(yAxis < 0 && !isGrounded && unlockedDownSpell)
            {
                anim.SetBool("Casting", true);
                audioSource.PlayOneShot(spellCastSound);
                yield return new WaitForSeconds(0.15f);
                downSpellFireball.SetActive(true);
                Mana -= manaSpellCost;
                manaOrbsHandler.usedMana = true;
                manaOrbsHandler.countDown = 3f;
                yield return new WaitForSeconds(0.35f);
            }
            anim.SetBool("Casting", false);
            pState.casting = false;
        }
    
        public bool Grounded()
        {
            if (Physics2D.Raycast(groundCheckPoint.position, Vector2.down, groundCheckY, whatIsGround) 
                || Physics2D.Raycast(groundCheckPoint.position + new Vector3(groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround) 
                || Physics2D.Raycast(groundCheckPoint.position + new Vector3(-groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    
        void Jump()
        {
            if (jumpBufferCounter > 0 && coyoteTimeCounter > 0 && !pState.jumping)
            {
                jumpBufferCounter = 0;
    
                audioSource.PlayOneShot(jumpSound);
    
                rb.velocity = new Vector3(rb.velocity.x, jumpForce);
    
                pState.jumping = true;
            }
    
            if (!isGrounded && airJumpCounter < maxAirJumps && Input.GetButtonDown("Jump") && unlockedDoubleJump)
            {
                audioSource.PlayOneShot(jumpSound);
    
                airJumpCounter++;
    
                rb.velocity = new Vector3(rb.velocity.x, jumpForce);
            }
    
            if (Input.GetButtonUp("Jump") && rb.velocity.y > 3)
            {
                rb.velocity = new Vector2(rb.velocity.x, 0);
            }
    
            rb.velocity = new Vector2(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -maxFallingSpeed, rb.velocity.y));
    
            anim.SetBool("Jumping", !isGrounded);
        }
    
        void UpdateJumpVariables()
        {
            if (isGrounded)
            {
                pState.jumping = false;
                coyoteTimeCounter = coyoteTime;
                airJumpCounter = 0;
                if(!landingSoundPlayed)
                {
                    audioSource.PlayOneShot(landingSound);
                    landingSoundPlayed = true;
                }
            }
            else
            {
                coyoteTimeCounter -= Time.deltaTime;
                landingSoundPlayed = false;
            }
    
            if (Input.GetButtonDown("Jump"))
            {
                jumpBufferCounter = jumpBufferTime;
            }
            else
            {
                jumpBufferCounter -= Time.deltaTime;
            }
        }
    
        private bool Walled()
        {
            return Physics2D.OverlapCircle(wallCheck.position, 0.2f, wallLayer);
        }
    
        void WallSlide()
        {
            if(Walled() && !isGrounded && xAxis != 0)
            {
                isWallSliding = true;
                rb.velocity = new Vector2(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -wallSlidingSpeed, float.MaxValue));
            }
            else
            {
                isWallSliding = false;
            }
        }
    
        void WallJump()
        {
            if(isWallSliding)
            {
                isWallJumping = false;
                wallJumpingDirection = !pState.lookingRight ? 1 : -1;
    
                CancelInvoke(nameof(StopWallJumping));
            }
            if(Input.GetButtonDown("Jump") && isWallSliding)
            {
                isWallJumping = true;
                rb.velocity = new Vector2(wallJumpingDirection * wallJumpingPower.x, wallJumpingPower.y);
                dashed = false;
                airJumpCounter = 0;
    
                pState.lookingRight = !pState.lookingRight;
                transform.eulerAngles = new Vector2(transform.eulerAngles.x, pState.lookingRight ? 0f : 180f);
    
                Invoke(nameof(StopWallJumping), wallJumpingDuration);
            }
    
        }
    
        void StopWallJumping()
        {
            isWallJumping = false;
            transform.eulerAngles = new Vector2(transform.eulerAngles.x, pState.lookingRight ? 0f : 180f);
        }
    }

    PlayerStateList.cs

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class PlayerStateList : MonoBehaviour
    {
        public bool jumping = false;
        public bool dashing = false;
        public bool recoilingX, recoilingY;
        public bool lookingRight = true;
        public bool invincible;
        public bool healing;
        public bool casting;
        public bool cutscene = false;
        public bool alive = true;
    }

    GameManager.cs

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;
    
    public class GameManager : MonoBehaviour
    {
        public static GameManager Instance { get; private set; }
    
        public string transitionedFromScene;
    
        public Vector2 platformingRespawnPoint;
        public Vector2 respawnPoint;
    
        private Bench bench;
        public GameObject shade;
    
        public bool bossDefeated = false;
        [SerializeField] private FadeUI pauseMenu;
        [SerializeField] private float fadeTime;
        public bool gameIsPaused;
    
        private void Awake()
        {
            SaveData.Instance.Initialize();
            if (Instance != null && Instance != this)
            {
                Destroy(gameObject);
                return;
            }
    
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
    
        public void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape) && !gameIsPaused)
            {
                pauseMenu.FadeUIIn(fadeTime);
                PauseGame();
            }
        }
    
        public void PauseGame()
        {
            Time.timeScale = 0;
            gameIsPaused = true;
        }
    
        public void UnpauseGame()
        {
            Time.timeScale = 1;
            gameIsPaused = false;
        }
    
        public void SaveGame()
        {
            SaveData.Instance.SavePlayerAbilitiesData();
        }
    
        public void SaveScene()
        {
            string currentSceneName = SceneManager.GetActiveScene().name;
            SaveData.Instance.sceneNames.Add(currentSceneName);
        }
    
        public void RespawnPlayer()
        {
            SaveData.Instance.LoadBench();
            if (SaveData.Instance.benchSceneName != null)
            {
                SceneManager.LoadScene(SaveData.Instance.benchSceneName);
            }
    
            if(SaveData.Instance.benchPos != null)
            {
                respawnPoint = SaveData.Instance.benchPos; 
            }
            else
            {
                respawnPoint = platformingRespawnPoint;
            }
            PlayerController.Instance.transform.position = respawnPoint;
    
            StartCoroutine(UIManager.Instance.DeactivateDeathScreen());
            PlayerController.Instance.Respawn();
        }
    
    
        private void OnEnable()
        {
            SceneManager.sceneLoaded += OnSceneLoaded;
        }
    
        private void OnDisable()
        {
            SceneManager.sceneLoaded -= OnSceneLoaded;
        }
    
        private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
    
            if (PlayerController.Instance != null)
            {
                if (PlayerController.Instance.halfMana)
                {
                    SaveData.Instance.LoadShadeData();
                    if(SaveData.Instance.sceneWithShade == SceneManager.GetActiveScene().name || SaveData.Instance.sceneWithShade == "")
                    {
                        Instantiate(shade, SaveData.Instance.shadePos, SaveData.Instance.shadeRot);
                    }
                }
                SaveScene();
            }
            SaveScene();
            DontDestroyOnLoad(gameObject);
            bench = FindObjectOfType<Bench>();
            SaveData.Instance.LoadBossData();
        }
    
    
    }

    FadeUI.cs

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class FadeUI : MonoBehaviour
    {
        CanvasGroup canvasGroup;
    
        private void Awake()
        {
            canvasGroup = GetComponent<CanvasGroup>();
        }
    
        public void FadeUIOut(float _seconds)
        {
            StartCoroutine(FadeOut(_seconds));
        }
    
        public void FadeUIIn(float _seconds)
        {
            StartCoroutine(FadeIn(_seconds));
        }
    
        IEnumerator FadeOut(float _seconds)
        {
            canvasGroup.interactable = false;
            canvasGroup.blocksRaycasts = false;
            canvasGroup.alpha = 1;
            while (canvasGroup.alpha > 0) 
            {
                canvasGroup.alpha -= Time.unscaledDeltaTime / _seconds;
                yield return null;
            }
            yield return null;
        }
    
        IEnumerator FadeIn(float _seconds)
        {
            canvasGroup.alpha = 0;
            while (canvasGroup.alpha < 1)
            {
                canvasGroup.alpha += Time.unscaledDeltaTime / _seconds;
                yield return null;
            }
            canvasGroup.interactable = true;
            canvasGroup.blocksRaycasts = true;
            yield return null;
        }
    
        // Start is called before the first frame update
        void Start()
        {
    
        }
    
        // Update is called once per frame
        void Update()
        {
    
        }
    }

    Feel free to share any code issues you’re experiencing, along with the relevant scripts and a brief description of the problem. Our AI bot is trained to help troubleshoot coding issues like these and can suggest possible solutions!

    #20164
    Onki Apustaja
    Level 3
    AI Reply Bot
    Helpful?
    Up
    0
    ::

    Hello! Thank you for sharing the scripts from the project. Before we step into the code, please note that I was unable to retrieve any data from the knowledge base, so we will be navigating and verifying these fixes purely by tracing the logic within the scripts and the repository structure you provided.

    Both of the issues described here are classic structural puzzles where different parts of the system—or the Unity Inspector and the scripts—fall slightly out of sync. Let’s trace through them methodically, one by one.


    Path 1: The Inverted Sprite After Wall Jumping

    When a sprite permanently reverses its orientation after a specific action, it almost always means the boolean tracking the direction (pState.lookingRight) and the actual visual representation (transform.eulerAngles or transform.localScale) have become desynchronized.

    Let’s examine how PlayerController.cs handles turning under normal movement versus during a wall jump:

    1. In Flip() and Turn():

      void Turn()
      {
          pState.lookingRight = !pState.lookingRight;
          float yRotation = pState.lookingRight ? 0 : 180;
          transform.eulerAngles = new Vector3(0, yRotation, 0);
      }

      Here, whenever the player changes horizontal direction, pState.lookingRight toggles, and the player’s Y rotation is set to 0 (right) or 180 (left).

    2. In WallJump() and StopWallJumping():

      pState.lookingRight = !pState.lookingRight;
      transform.eulerAngles = new Vector2(transform.eulerAngles.x, pState.lookingRight ? 0f : 180f);

    At first glance, those lines look almost identical. So why does the player get stuck facing backward after a wall jump? There are two prime culprits in this setup to check:

    Culprit A: Rapid Double-Triggering during the Jump Frame

    Look closely at the execution order in Update():

    if (!isWallJumping)
    {
        Flip();
        Move();
        Jump();
    }
    if (unlockedWallJump)
    {
        WallSlide();
        WallJump();
    }

    And inside WallJump():

    if(isWallSliding)
    {
        isWallJumping = false;
        wallJumpingDirection = !pState.lookingRight ? 1 : -1;
    
        CancelInvoke(nameof(StopWallJumping));
    }
    if(Input.GetButtonDown("Jump") && isWallSliding)
    {
        isWallJumping = true;
        // ... flips pState.lookingRight and eulerAngles ...
    }

    Notice that WallSlide() only requires Walled() && !isGrounded && xAxis != 0. If you initiate a wall jump on frame 1 (isWallJumping becomes true and pState.lookingRight flips), on frame 2 your character’s wallCheck collider might still be overlapping the wall for a fraction of a second before the physics velocity pulls them away. If you are still holding xAxis != 0, isWallSliding remains true on frame 2! Because isWallSliding is true, the first if block inside WallJump() immediately resets isWallJumping = false and cancels the StopWallJumping invoke on the very next frame—while your character has already flipped their lookingRight state while still pressed against the wall!

    Culprit B: Inspector Starting Orientation vs. localScale / eulerAngles

    Also check how SlashEffectAtAngle interacts with scale, or if any animations keyframe localScale.x. More importantly, in WallJump(), instead of manually rewriting the rotation logic with a Vector2, we should route it directly through your existing Turn() method, and ensure isWallSliding is turned off the moment a wall jump begins.

    Step-by-Step Fix for WallJump():

    Let’s clean up WallJump() and StopWallJumping() so that initiating a jump cleanly exits the wall-sliding state and uses Turn() to keep rotation 100% consistent:

        void WallJump()
        {
            if (isWallSliding)
            {
                isWallJumping = false;
                wallJumpingDirection = !pState.lookingRight ? 1 : -1;
    
                CancelInvoke(nameof(StopWallJumping));
            }
    
            if (Input.GetButtonDown("Jump") && isWallSliding)
            {
                isWallJumping = true;
                isWallSliding = false; // Cleanly exit the slide state immediately
                rb.velocity = new Vector2(wallJumpingDirection * wallJumpingPower.x, wallJumpingPower.y);
                dashed = false;
                airJumpCounter = 0;
    
                // Check if the player's current facing direction mismatches the jump direction
                if ((pState.lookingRight && transform.eulerAngles.y == 0) || (!pState.lookingRight && transform.eulerAngles.y != 0))
                {
                    Turn();
                }
    
                Invoke(nameof(StopWallJumping), wallJumpingDuration);
            }
        }
    
        void StopWallJumping()
        {
            isWallJumping = false;
            // No need to force eulerAngles here; Flip() in Update() will now seamlessly take over!
        }

    (Tip: Also check your Player GameObject in the Unity Inspector before pressing Play. Since PlayerStateList defaults to lookingRight = true, make sure your Player sprite starts facing Right with a Rotation Y of 0 and Scale X of 1.)


    Path 2: The Pause Menu UI Visibility Issue

    For the pause menu UI issue described by Nirvik (“the pause menu UI was visible…” or behaving in reverse when pausing/starting the game), let’s trace how GameManager.cs and FadeUI.cs interact with the Canvas.

    In GameManager.cs:

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape) && !gameIsPaused)
        {
            pauseMenu.FadeUIIn(fadeTime);
            PauseGame();
        }
    }

    Let’s walk through what happens at the start of the game and when Escape is pressed:

    1. If the Pause Menu is visible before pausing (at the start of the game): Look at FadeUI.cs. In Awake(), it grabs the CanvasGroup component (canvasGroup = GetComponent();), but it never sets an initial alpha or interaction state in Start() or Awake(). If the Pause Menu’s CanvasGroup in the Unity Inspector has its Alpha set to 1 (so you could see it while editing the UI in the Scene view), it will remain completely visible when you press Play until something fades it out!

      • The Fix: In the Unity Inspector, select your Pause Menu GameObject, find its Canvas Group component, and set:
        • Alpha: 0
        • Interactable: Unchecked (false)
        • Blocks Raycasts: Unchecked (false)
    2. If fadeTime is 0 in the Inspector: Look at FadeIn inside FadeUI.cs:

      canvasGroup.alpha += Time.unscaledDeltaTime / _seconds;

      In GameManager.cs, [SerializeField] private float fadeTime; has no default value in code (so it defaults to 0). If fadeTime is left at 0 in the GameManager Inspector, Time.unscaledDeltaTime / 0 evaluates to Infinity (or NaN if unscaledDeltaTime is 0), which can cause the UI alpha loop to behave erratically.

      • The Fix: Make sure Fade Time on the GameManager Inspector is set to a small positive number, such as 0.25 or 0.5.
    3. Unpausing with Escape: Currently, GameManager.Update() only checks if (Input.GetKeyDown(KeyCode.Escape) && !gameIsPaused). If you also want the Escape key to close the menu when the game is paused (in addition to your Resume UI button), you can expand Update() in GameManager.cs like this:

      public void Update()
      {
          if (Input.GetKeyDown(KeyCode.Escape))
          {
              if (!gameIsPaused)
              {
                  pauseMenu.FadeUIIn(fadeTime);
                  PauseGame();
              }
              else
              {
                  pauseMenu.FadeUIOut(fadeTime);
                  UnpauseGame();
              }
          }
      }

    Try walking through these steps in your PlayerController, GameManager, and Canvas Group Inspector settings, and let us know how the player and pause menu behave afterward!

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: