用意されている機能を駆使して衝突判定を行いたいとき
●方法1 colliderを使いイベントを拾う
UnityのRigidbodyとColliderで衝突判定 - Qiita
Unityで物理シミュレーションとイベントハンドラの挙動 - Qiita
ちなみにBoxCollider はAxis Aligned Bounding Box なので、回転には対応しない。 回転させても、それの最大のbounding boxになる。
それが困る場合はMeshCollider使う。Sphereやカプセルもある(あんまり調べてない)。
●方法2 colliderとの衝突を自分で実装
Bounds.Contains Unity - スクリプティング API: Bounds.Contains
Collider.ClosestPointOnBounds Unity - スクリプティング API: Collider.ClosestPointOnBounds
などを駆使する。
●方法3 rayを飛ばす
MeshColliderがついてないと検出しないっぽい
public LayerMask _mask;//レイヤーで対象を絞る void Update() { //レイの設定 ray = new Ray( _camera.transform.position, _camera.transform.TransformDirection(Vector3.forward) ); //レイキャスト(原点, 飛ばす方向, 衝突した情報, 長さ) if (Physics.Raycast(ray, out hit, Mathf.Infinity,_mask)) { //レイを可視化 Debug.DrawRay( _camera.transform.position, _camera.transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow ); _target.transform.position = hit.point; _target.SetActive(true); }else{ _target.SetActive(false); } }
あとhit.normalというのを使うと衝突地点のnormalが取得できるので便利。
allというのもある https://docs.unity3d.com/ja/current/ScriptReference/Physics.RaycastAll.html