【问题标题】:How do I adjust Unity 2D jump velocity?如何调整 Unity 2D 跳跃速度?
【发布时间】:2021-07-27 04:24:44
【问题描述】:

我目前正在关注 Jason Weimann 关于如何在 Unity 中制作 2D 飞扬小鸟游戏的 YouTube 教程。到目前为止,一切都运行良好,直到您编写代码以使玩家跳跃并更改跳跃速度的部分。玩家可以跳得很好,但我不知道如何改变速度。我已经尝试在视频上发表评论以寻求帮助,但尚未得到回复。我对编程很陌生,对 C# 了解不多。到目前为止,这是我的代码:

公共类播放器:MonoBehaviour { 私有 Vector2 jumpVelocity;

// Update is called once per frame
void Update()
{
    if(Input.GetButtonDown("Fire1"))
    {
        GetComponent<Rigidbody2D>().velocity = jumpVelocity;
    }
}

}

感谢任何帮助!

【问题讨论】:

    标签: c# unity3d 2d


    【解决方案1】:

    您需要熟悉 c# 编码。

    public class Player : MonoBehaviour { 
      [SerializeField] // now you can set it from Inspector for Player script
      private Vector2 jumpVelocity;
      
      void Awake() {
        jumpVelocity = new Vector2(0f, 1f); // or set the values for x n y axes in code
      }
      void Update()
      {
        if(Input.GetButtonDown("Fire1"))
        {
            GetComponent<Rigidbody2D>().velocity = jumpVelocity;
        }
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      2D 中的速度是一个向量单位,它有 X 和 Y 轴 所以如果给Vector2赋值一个浮点变量,就会报错。您需要将其分配给 Vector2。像这样

      GetComponent&lt;Rigidbody2D&gt;().velocity = new Vector2(0f, 1f);

      或者像上面的答案一样声明一个 Vector2 jumpVelocity 并更改

      new Vector2(0f, 1f)jumpVelocity

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多