LoginSignup
0
0

More than 1 year has passed since last update.

Rigidbody2D.IsTouching(Collider2D)による接地判定時にlocalScaleで左右反転すると判定がブレる事がある

Posted at

はじめに

本記事はUnityで2Dアクションゲームを作っている時に躓いた点を備忘録として記録しております。
こうすると判定がブレないよ!という実装方法がありましたらコメントで教えて頂けると幸いです(;'∀')

参考記事

キャラクターの接地判定を行うにあたって、以下の記事を参考にさせて頂きました。
ColliderやRayを使った接地判定より使いやすいので、毎度使わせて頂いております!感謝!

今回問題になった事

で、今回何が問題になったのかですが…

2Dアクションゲームでキャラクターが左右に移動する際、キャラクター反転の方法として
「transform.localScaleのx値をマイナス値にする」事で再現している記事は多いかと思います。

僕もこの方法で実装していたのですが、
参考記事に記載した「Rigidbody2D.IsTouching(Collider2D)」による接地判定と組み合わせて使っていると、
左右を振り向いた際に接地判定がfalseを返すタイミングがありました。

▼接地してる時はTrue
1.png

左右に動かすとFalseが返るタイミングがある!
2.png

解決策

結局、左右反転については「SpriteRenderer.FlipX」を使う事で解決しました。
SpineAnimationを使っている場合は「SkeletonAnimation.skeleton.ScaleX」となります。

問題が起きたコード

こちらになります。本番コードからの切り抜きなので説明不足な部分もありますがご了承下さい。

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

public class TestController : MonoBehaviour
{
    [SerializeField] private ContactFilter2D filter2d;
    float movespeed = 1.5f;
    bool isTouched;
    Vector3 move_control;
    protected PlayerInput playerinput;
    Rigidbody2D rb;

    protected void Awake()
    {
        playerinput = new PlayerInput();
        playerinput.Enable();
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        isTouched = GetComponent<Rigidbody2D>().IsTouching(filter2d);

        Vector2 newvec = Vector2.zero;
        move_control = playerinput.Player.Move.ReadValue<Vector2>();

        if (move_control.x != 0.0f)
        {
            Vector3 ls = transform.localScale;

            if (move_control.x > 0.0f)
            {
                newvec.x = movespeed;
                ls.x = -Mathf.Abs(ls.x);
            }
            else if (move_control.x < 0.0f)
            {
                newvec.x = -movespeed;
                ls.x = Mathf.Abs(ls.x);
            }
            transform.localScale = ls;
        }
        //移動速度を適用する。
        rb.velocity = newvec;

        print("?:" + isTouched);
    }
}

0
0
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
0