简体   繁体   English

在 Unity 中通过触摸 C# 改变重力

[英]Change Gravity with a Touch C# in Unity

i wonne make a game where the Gravity changes form 1 enter image description here to -1 enter image description here when i touch one Button and back when i touch the other button Button.我不会制作一个重力变化形式的游戏 1在此处输入图像描述到 -1 在我触摸一个按钮时在此处输入图像描述,当我触摸另一个按钮时返回。 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;
 }





}

} }

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

Graviyscale affects how much gravity will effect the rigidbody, I'm assuming its not working because it plateaus at 0 = no effect. Graviyscale 会影响重力对刚体的影响,我假设它不起作用,因为它在 0 处停滞不前 = 没有效果。 You might have to take a different approach, something like您可能必须采取不同的方法,例如

rb.gravityScale = -1;

replace with用。。。来代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM