Unityジャンプのやり方


2段ジャンプ

Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    private Rigidbody rb;
    public int Jumpflg;
    public float Jump = 300;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        Jumpflg = 0;  //ジャンプの初期化
    }
}

ここまではジャンプに必要なコードです。

次に

Player
public class Player : MonoBehaviour
{
    void Update()
    {
        if (Jumpflg <= 1)  //2段ジャンプ
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.AddForce(Vector3.up * Jump);
                Jumpflg++;
            }
        }
    }
}

Jumpflgをpublicにしたことでインスペクター上でJumpflgの値が見れるようになりました。
Jumpflgが1以下だったらスペースキーを押せてAddForceで上向きに力をかけており、
一回スペースキーを押すごとにJumpflgが1ずつ上がっていきます。
これにより、1回ジャンプでJumpflgは0から1になります。1になったらif(Jumpflg <= 1)の
条件式が成立するのでもう一回スペースキーを押し、ジャンプすることが可能になります。
ちなみに、if(Jumpflg == 0)は1回のみジャンプが可能、if(Jumpflg <= 2)は3回ジャンプが可能になります。

しかし、上記の記述のみだと再生してから2回しかジャンプ出来ないと言うことになります。
ゲームの場合、地面に着地するごとに2回ジャンプしたいですよね。
そうするためには下記の記述が必要になります。
地面とPlayerにcolliderをつけて、colliderに触れたらJumpflgを0にするという記述が必要です。
ジャンプを2回するとJumpflgが2になり、上記のif (Jumpflg <= 1)の条件式は不成立になって
しまいます。
下記のような記述だと、地面に着地するとJumpflgが0になり、地面着地後、上記のif (Jumpflg <= 1)の条件式が成立するようになります。

Player
public class Player : MonoBehaviour
{
    void OnCollisionEnter(Collision collision)  //ジャンプ、地面に触れると
    {
        Jumpflg = 0;  //Jumpflgを0にする
    }
}

まとめ

Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    private Rigidbody rb;
    public int Jumpflg;
    public float Jump = 300;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        Jumpflg = 0;  //ジャンプの初期化
    }

void Update()
    {
        if (Jumpflg <= 1)  //2段ジャンプ
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.AddForce(Vector3.up * Jump);
                Jumpflg++;
            }
        }
    }

void OnCollisionEnter(Collision collision)  //ジャンプ、地面に触れると
    {
        Jumpflg = 0;  //Jumpflgを0にする
    }
}

こうやって記述すると2段ジャンプが出来るようになりました!!