Search code examples
c#unity-game-enginegravity

Change Gravity with a Touch C# in Unity


i wonne make a game where the Gravity changes form 1enter image description here to -1enter image description here when i touch one Button and back when i touch the other button Button. In the Beginning it works but then it just stops working

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

       public class Button : MonoBehaviour
     {
       private Rigidbody2D rb;

       private bool moveUp;
     private bool MoveDown;

   // Start is called before the first frame update
     void Start()
     {
       rb = GetComponent<Rigidbody2D>();

      moveUp = false;
     MoveDown = false;

    }


         public void PionterDownRight(){
        moveUp = true;
          }
          public void PionterUpRight(){
           moveUp=false;
           }

       public void PionterDownLeft(){
          MoveDown= true;
          }
         public void PionterUpLeft(){
        MoveDown = false;
          }

     // Update is called once per frame
void Update()
{
 if(moveUp){
  rb.gravityScale = -1;
 }

 if (MoveDown){
       rb.gravityScale = 1;
 }





}

}


Solution

  • I recommend having only one bool variable:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class Button : MonoBehaviour
    {
        private Rigidbody2D rb;
    
        private bool moveDown = true;
    
        // Start is called before the first frame update
        void Start()
        {
            rb = GetComponent<Rigidbody2D>();
        }
    
    
        public void PionterDownRight()
        {
            moveDown = false;
        }
        public void PionterUpRight()
        {
            moveDown = true;
        }
    
        public void PionterDownLeft()
        {
            moveDown = true;
        }
        public void PionterUpLeft()
        {
            moveDown = false;
        }
    
        // Update is called once per frame
        void Update()
        {
            if (moveDown == true)
            {
                rb.gravityScale = 1;
            }
            else
            {
                rb.gravityScale = -1;
            }
        }
    }