Meiryo’s blog

やってみて詰まったことを備忘録として残すブログ

【Unity 2D】着地判定をしてジャンプをする方法

この間アクションゲームを作った時に
ジャンプ機能を実装したので
備忘録として残しておきます。

スクリプト

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

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerJumper : MonoBehaviour
{
    [SerializeField]
    private Transform _touchedChecker_L;
    [SerializeField]
    private Transform _touchedChecker_C;
    [SerializeField]
    private Transform _touchedChecker_R;

    [SerializeField]
    private float _jumpPower = 4;
    private Rigidbody2D Rb { get; set; }
    private bool Grounded { get; set; } = false;
    private bool PrevGrounded { get; set; } = false;
    private bool Jumped { get; set; } = false;

    private void Start()
    {
        Rb = GetComponent<Rigidbody2D>();
    }

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

    private void FixedUpdate()
    {
        //接地チェック
        PrevGrounded = Grounded;
        Grounded = false;
        Grounded = IsGrounded();

        //着地チェック
        if (Jumped)
        {
            if (Grounded && !PrevGrounded)
            {
                Jumped = false;
            }
        }
    }

    /// <summary>
    /// 足が何かに触れているかを判定する
    /// </summary>
    /// <returns>何かに触れていればtrue、何も触れていなければfalse</returns>
    bool IsGrounded()
    {
        var touchCheckCols = new Collider2D[3][];
        touchCheckCols[0] = Physics2D.OverlapPointAll(_touchedChecker_L.position);
        touchCheckCols[1] = Physics2D.OverlapPointAll(_touchedChecker_C.position);
        touchCheckCols[2] = Physics2D.OverlapPointAll(_touchedChecker_R.position);

        foreach (Collider2D[] touchCheckList in touchCheckCols)
        {
            foreach (Collider2D touchCheck in touchCheckList)
            {
                if (touchCheck == null) continue;

                if (!touchCheck.isTrigger)
                {
                    return true;
                }
            }
        }
        return false;
    }

    public void Jump()
    {
        if (!Jumped)
        {
            Jumped = true;
            Rb.velocity = new Vector2(Rb.velocity.x, _jumpPower);
        }
    }
}

動かすとこんな感じです。
f:id:meimaru:20210603002949g:plain

着地判定

着地判定はプレイヤーの足元に
空のオブジェクト3つを付け、
それらがisTriggerではない
Collider2Dを持つオブジェクトに触れたら
着地しているとみなすという
処理をしています。

f:id:meimaru:20210603003118p:plain

この着地判定とジャンプの方法は
下記の本を参考にしました。
もう結構古い本なのですが
「アクションゲームを作る時の考え方」が
学べていい本なのでおすすめです。