Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active December 22, 2015 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/6475891 to your computer and use it in GitHub Desktop.
Save tsubaki/6475891 to your computer and use it in GitHub Desktop.
1個のオブジェクトでも複数回接触判定を返すRaycast
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MultiHitRay
{
public static List<Vector3> CheckMultiHitRay(Vector3 position, Vector3 direction, float length, LayerMask mask)
{
List<Vector3> list = new List<Vector3>();
// 双方向Rayで大雑把な形状を取得
RaycastHit[] foward = Physics.RaycastAll (position, direction, length, mask);
RaycastHit[] back = Physics.RaycastAll (position + direction * length, direction * -1, length, mask);
// 外枠のポイント一覧を登録
foreach (RaycastHit hit in foward) {
list.Add (hit.point);
}
foreach (RaycastHit hit in back) {
list.Add (hit.point);
}
// 内部のコライダーを取得
foreach (RaycastHit fowardHit in foward) {
foreach (RaycastHit backHit in back) {
if (fowardHit.collider == backHit.collider) {
float maxDistance = Vector3.Distance (fowardHit.point, backHit.point);
CheckInnerObject(fowardHit.collider, fowardHit.point, direction, maxDistance, list);
CheckInnerObject(fowardHit.collider, backHit.point, direction*-1, maxDistance, list);
}
}
}
return list;
}
public static void CheckInnerObject (Collider hit, Vector3 currentPoint, Vector3 direction, float distance, List<Vector3> list )
{
RaycastHit inMeshHit;
while (hit.Raycast (new Ray (currentPoint + direction * 0.1f, direction), out inMeshHit, distance)) {
list.Add (inMeshHit.point);
currentPoint = inMeshHit.point;
distance -= inMeshHit.distance;
}
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class Sample : MonoBehaviour
{
#region UNITY_DELEGATE
[Range(0.1f, 30f)]
public float Length = 20;
public LayerMask Mask;
private List<Vector3> posList = new List<Vector3> ();
void Update ()
{
posList.Clear ();
posList.AddRange (MultiHitRay.CheckMultiHitRay (transform.position, transform.forward, Length, Mask));
}
void OnDrawGizmos ()
{
if (posList == null) {
return;
}
Gizmos.color = Color.white;
Gizmos.DrawSphere (transform.position, 0.1f);
Gizmos.DrawSphere (transform.position + transform.forward * Length, 0.1f);
Gizmos.DrawLine (transform.position, transform.position + transform.forward * Length);
Gizmos.color = Color.red;
foreach (Vector3 pos in posList) {
Gizmos.DrawSphere (pos, 0.1f);
}
Gizmos.color = Color.white;
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment