2つの領域が重なっているかを調べるプログラム。
通常は当たり判定(Collidor
)のBounds.Contains()
を使えばよいのですが、諸事情で自作することにしました。
ChatGPT-4で出力したコードに、少し改変を加えたものです。インターフェースは Collidor.Bounds.Contains()
に似せてあります。
コード
Bound.cs
using UnityEngine; // ChatGPT-4 2023/5/22 // 領域の重なりチェック public class Bound { public Vector3 MinBounds; //{ get; set; } public Vector3 MaxBounds; //{ get; set; } public bool Contains(Bound otherBound, bool strict = true) { if ( strict ) { // 完全に含まれている場合 return (otherBound.MinBounds.x >= MinBounds.x && otherBound.MaxBounds.x <= MaxBounds.x && otherBound.MinBounds.y >= MinBounds.y && otherBound.MaxBounds.y <= MaxBounds.y && otherBound.MinBounds.z >= MinBounds.z && otherBound.MaxBounds.z <= MaxBounds.z); } else { // 一部分だけでも重なっている場合 return (otherBound.MinBounds.x <= MaxBounds.x && otherBound.MaxBounds.x >= MinBounds.x && otherBound.MinBounds.y <= MaxBounds.y && otherBound.MaxBounds.y >= MinBounds.y && otherBound.MinBounds.z <= MaxBounds.z && otherBound.MaxBounds.z >= MinBounds.z); } } }
使い方
// ベース:どの領域に属する or 重なる Bound boundBase = new Bound(); boundBase.MinBounds = new Vector3(0f, 0f, 0f); boundBase.MaxBounds = new Vector3(10f, 10f, 10f); // 比較対象:どの領域について調査するか? Bound boundCheckTarget = new Bound(); boundCheckTarget.MinBounds = new Vector3(2f, 2f, 2f); boundCheckTarget.MaxBounds = new Vector3(8f, 8f, 8f); // 比較 bool isContained = boundBase.Contains( boundCheckTarget, true ); if (isContained){ Debug.Log("領域は含まれています。"); } else { Debug.Log("領域は含まれていません。"); }
strict指定について
strict
を付けた場合、比較するオブジェクトが比較元に完全に含まれている場合だけ TRUE
になります。strict
を付けなかった場合、領域に重なっている部分さえあれば TRUE
になります。
