【问题标题】:Unity 2d jumping scriptunity 2d 跳跃脚本
【发布时间】:2020-06-27 00:23:47
【问题描述】:

有没有人有一个很好的统一的2d游戏跳跃脚本?我的代码可以运行,但还远远没有跳起来,它看起来像是在飞。

using UnityEngine;
using System.Collections;

public class movingplayer : MonoBehaviour {

public Vector2 speed = new Vector2(10,10);

private Vector2 movement = new Vector2(1,1);

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    float inputX = Input.GetAxis ("Horizontal");
    float inputY = Input.GetAxis ("Vertical");

    movement = new Vector2(
        speed.x * inputX,
        speed.y * inputY);

    if (Input.GetKeyDown ("space")){
                         transform.Translate(Vector3.up * 260 * Time.deltaTime, Space.World);
                 } 

}
void FixedUpdate()
{
    // 5 - Move the game object
    rigidbody2D.velocity = movement;
    //rigidbody2D.AddForce(movement);

}
}

【问题讨论】:

    标签: c# unity3d physics


    【解决方案1】:

    通常对于跳跃的人使用Rigidbody2D.AddForceForcemode.Impulse。看起来您的对象在 Y 轴上被推动一次,它会由于重力而自动下落。

    例子:

    rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
    

    【讨论】:

      【解决方案2】:

      上面的答案现在在 Unity 5 或更高版本中已过时。改用这个!

      GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);
      

      我还想补充一点,这使得跳跃高度超级私密,只能在脚本中编辑,所以这就是我所做的......

          public float playerSpeed;  //allows us to be able to change speed in Unity
      public Vector2 jumpHeight;
      
      // Use this for initialization
      void Start () {
      
      }
      // Update is called once per frame
      void Update ()
      {
          transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run
      
          if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
          {
              GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
      

      这使得您可以在 Unity 中编辑跳跃高度而无需返回脚本。

      旁注 - 我想对上面的答案发表评论,但我不能,因为我是新来的。 :)

      【讨论】:

      • 对我没有任何帮助。
      【解决方案3】:

      使用刚体组件的 Addforce() 方法,确保刚体连接到对象并启用重力, 像这样的

      gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
      gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 
      

      查看哪些组合和哪些值符合您的要求并相应地使用。 希望对你有帮助

      【讨论】:

        猜你喜欢
        • 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
        相关资源
        最近更新 更多