[Unity 3D] 二段ジャンプを実装する方法。

(2022/03/22)
3Dで二段ジャンプを実装する方法。

使用したUnityのバージョン:2020.3.30f1

二段ジャンプを実装する方法

地面となるゲームオブジェクトに、groundという名前のタグをつけて、下のコードのスクリプトを、二段ジャンプさせたいオブジェクトにアタッチすれば二段ジャンプが実装できます。

  Rigidbody rb;

  int stage = 0;

  public float speed = 10f;

    void Start()
    {
      rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
      if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) {
        this.transform.position += transform.forward * speed * Time.deltaTime;
      }

      if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) {
        this.transform.position -= transform.forward * speed * Time.deltaTime;
      }

      if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) {
        this.transform.Rotate(0,-1f,0);
      }

      if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) {
        this.transform.Rotate(0,1f,0);
      }

      if (Input.GetKeyDown(KeyCode.Space))
      {
        Jump();
      }

    }

    void OnCollisionEnter(Collision other)
    {
      if (other.gameObject.tag == "ground")
       {
        stage = 0;
       }
    }

    void Jump()
    {
        if (stage <= 1)
        {
          stage++;
          rb.AddForce(transform.up * 10f, ForceMode.Impulse);
          return;
        }
     }

しかし上のコードでは、二段目のジャンプをしようとした時スペースを押すタイミングによってジャンプする高さが変わってしまいます。

スペースを押す間隔を短くした場合
飛行するゲームオブジェクトの作り方。
スペースを押す間隔を長くした場合
飛行するゲームオブジェクトの作り方。

修正したコード

修正といっても、一行加えただけです。

  Rigidbody rb;

  int stage = 0;

  public float speed = 10f;

    void Start()
    {
      rb = GetComponent();
    }

    void Update()
    {
      if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) {
        this.transform.position += transform.forward * speed * Time.deltaTime;
      }

      if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) {
        this.transform.position -= transform.forward * speed * Time.deltaTime;
      }

      if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) {
        this.transform.Rotate(0,-1f,0);
      }

      if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) {
        this.transform.Rotate(0,1f,0);
      }

      if (Input.GetKeyDown(KeyCode.Space))
      {
        Jump();
      }

    }

    void OnCollisionEnter(Collision other)
    {
      if (other.gameObject.tag == "ground")
       {
        stage = 0;
       }
    }

    void Jump()
    {
        if (stage <= 1)
        {
          stage++;
          rb.velocity = Vector3.zero;
          rb.AddForce(transform.up * 10f, ForceMode.Impulse);
          return;
        }
     }

50行目に「rb.velocity = Vector3.zero;」を加えることでスペースを押す間隔に左右されずジャンプさせることができます。

 
他の記事も見る
 
  • プライバシーポリシー