頑張ってゲーム作ることにする #3キャラクターのジャンプを実装する

前回は左右の移動のみを実装したので、今回はサクッとジャンプ動作を実装したいと思います。
→地面に設置しているかどうかを判別して、空中ジャンプはとりあえずなしにしようと思うので、あまりサクッと実装はできなさそう

とりあえず、タイルマップにgroundという名前のタグを新たに付け地面だと認識できるようにします。
f:id:Neuman-I:20210325181249p:plain

つぎに、地面に設置しているかどうかを確かめるためのboxCollider2DをPlayerの足元に子オブジェクトとして作成しました。
f:id:Neuman-I:20210325181714p:plain

このGroundCheckオブジェクトにGroundCheckという名前のスクリプトをアタッチします。
このスクリプトには地面に設置している状態であるかどうかが分かるようにします。

計画では、PlayerオブジェクトはこのGroundCheckオブジェクト内のbool型の設置確認変数をジャンプボタンが押されるたびに見に行きます。
そして、変数が設置を表している場合のみジャンプすることにします。

groudcheck

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

public class GroundCheck : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    //if canJump is True, you can Jump!!
    public bool canJump = false;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag=="Ground")
        {
            canJump = true;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag=="Ground")
        {
            canJump = false;
        }
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.tag == "Ground")
        {
            canJump = true;
        }
    }

    public bool IsGround()
    {
        return canJump;
    }
}
>|| 

PlayerController
>|cs|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    // Player move speed
    const float MOVE_SPEED = 3;

    // Player jump power
    public float JUMP_POWER = 100;

    float moveSpeed;
    // Rigidbody2d setting
    private Rigidbody2D rb;

    //groundCheck
    public GroundCheck groundCheck;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void FixedUpdate()
    {
        float x = Input.GetAxis("Horizontal");

        if (x > 0)// move right
        {
            transform.localScale = new Vector2(1, 1);
            moveSpeed = MOVE_SPEED;
            Debug.Log("1");
        }
        else if (x < 0) // move left
        {
            transform.localScale = new Vector2(-1, 1);
            moveSpeed = -1 * MOVE_SPEED;
            Debug.Log("-1");
        }
        else 
        {
            moveSpeed = 0;
            Debug.Log("0");
        }

        rb.velocity = new Vector2(moveSpeed, rb.velocity.y);

        if (Input.GetKeyDown("space") && groundCheck.canJump)
        {
            rb.velocity = new Vector2(rb.velocity.x, JUMP_POWER);
        }
    }
}
>||

ジャンプはするし、2段ジャンプもしない
でもジャンプが反応するときと反応しないときがある...