7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Unity] Colliderのみで衝突判定を行う

Last updated at Posted at 2019-12-16

こんばんは、Arumiです!

今回はRigidbodyなしで衝突判定を行ってみましょう(๑•̀ㅂ•́)و✧

#実装

collider.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class PlayerCollider : MonoBehaviour
{
    // BoxCollider2D コンポーネント
    BoxCollider2D collider2d;

    // 衝突結果を格納 (最大5個まで)
    Collider2D[] results = new Collider2D[5];

    // 開始処理
    void Start ( )
    {
        // Colliderをキャッシュ
        collider2d = GetComponent<BoxCollider2D> ();
    }

    // 更新処理
    void Update ( )
    {
        if ( IsHitToEnemy ()  ) {
            Debug.Log ("衝突しています");
        }
    }

    // 敵との衝突判定
    bool IsHitToEnemy ( )
    {
        // collider2dと衝突しているcolliderの数が返ってくる
        int hitCount = collider2d.OverlapCollider(new ContactFilter2D(), results);

        if ( hitCount > 0 )
        {
            for ( int i = 0; i < hitCount; i++ )
            {
                // 衝突したオブジェクトのTagがEnemyならreturn
                if ( results [ i ].tag == "Enemy") 
                {
                    return true;
                }
            }
        }
        return false;
    }
}

BoxCollider2Dと先程のコンポーネントを取り付けたプレイヤー(仮)
player.jpg

BoxCollider2DとTagをEnemyにした敵オブジェクト(仮)
inspector.jpg

2つのオブジェクトを作り、重なるように配置したら再生してみてください

#結果
めっちゃ衝突してくれます
result.jpg

今回はここまで(`・ω・´)ゞ
ありがとうございました!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?