velocityで移動・ジャンプさせる

トップへ

参考ページ

https://futabazemi.net/unity/addforce_velocity_jump
 https://qiita.com/yuki2006/items/a60fc92e033dddcb3a83

どういうときに使うか

 transform.positionを直接操作したりAddforceしたりするより動きが自然な気がするよというお話。

どうするか

    // 横移動速度
    private float MOVE_SPEED = 4f;

    // ジャンプの高さ
    private float JUMP_SPEED = 8f;

    // 横移動入力状態(右が1・左が-1)
    private int inputX = 0;

    // 接地判定結果
    private bool isGround;

    void Update()
    {
        
        if (Input.GetKey(KeyCode.RightArrow)) 
        {
            inputX = 1;
        }
        else if (Input.GetKey(KeyCode.LeftArrow)) 
        {
            inputX = -1;
        }
        else 
        {
            inputX = 0;
        }

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

        CheckGround();
    }

    private void Jump() 
    {
        // ジャンプ移動
        rb.velocity = new Vector2(rb.velocity.x, JUMP_SPEED);
    }

    private void FixedUpdate()
    {
        if (inputX == 1) 
        {
            animator.SetInteger("direction", 1);
            rb.velocity = new Vector2(MOVE_SPEED, rb.velocity.y);
        }
        if (inputX == -1) 
        {
            animator.SetInteger("direction", -1);
            rb.velocity = new Vector2(-MOVE_SPEED, rb.velocity.y);
        }
        if (isGround && inputX == 0) 
        {
            rb.velocity = new Vector2(0, 0);
        }
    }

    private static float RAY_LENGTH = 0.5f;

    void CheckGround() 
    {
        /* 設置判定(足元だけバージョン) */
        Vector2 rayPosition = transform.position + new Vector3(0.5f, -1f, 0);
        Ray2D ray = new Ray2D(rayPosition, transform.up * -1);

        int layerMask = LayerMask.GetMask(new string[] {
            "Default"
        });

        RaycastHit2D hit = Physics2D.Raycast((Vector2)ray.origin, Vector2.down, RAY_LENGTH, layerMask);

        if (hit.collider == null) 
        {
            if (SystemConfig.Debug.ViewRayCast) 
            {
                Debug.DrawRay(ray.origin, ray.direction * RAY_LENGTH, Color.blue);
            }
            isGround = false;
        }
        else if (!isGround)
        {
            if (hit.collider.name == "Field") 
            {
                if (SystemConfig.Debug.ViewRayCast) 
                {
                    Debug.DrawRay(ray.origin, ray.direction * RAY_LENGTH, Color.red);
                    Debug.Log("着地");
                }
                isGround = true;
            }
            else
            {
                if (SystemConfig.Debug.ViewRayCast) 
                {
                    // 想定外
                    Debug.DrawRay(ray.origin, ray.direction * RAY_LENGTH, Color.red);
                }
            }
        } 
        else 
        {
            if (SystemConfig.Debug.ViewRayCast) 
            {
                Debug.DrawRay(ray.origin, ray.direction * RAY_LENGTH, Color.green);
            }
        }
    }