LoginSignup
0
2

More than 1 year has passed since last update.

Unityジャンプのやり方

Last updated at Posted at 2021-10-08

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段ジャンプが出来るようになりました!!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2