在 Unity 中使用 Touch C# 改变重力

Change Gravity with a Touch C# in Unity

我不会制作一个游戏,当我触摸一个按钮时重力从 1enter image description here to -1enter image description here 变化,当我触摸另一个按钮时重力变化。一开始它可以工作,但后来就停止工作了

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;
 }





}

}

我建议只有一个 bool 变量:

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;
        }
    }
}

Graviyscale 影响重力对刚体的影响,我假设它不起作用,因为它稳定在 0 = 没有效果。您可能需要采取不同的方法,例如

rb.gravityScale = -1;

替换为

rb.AddForce(new Vector2(0, 9.81f * 2));