可选是否打开矩阵变换,支持xyz三种朝向
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using UnityEngine; using System.Collections; using System.Collections.Generic; public class CapsuleDetection : MonoBehaviour { public enum Axis { X, Y, Z } public Transform comparePointTransform; public float radius; public float height; public Axis axis; public bool enableMatrix; bool ExecuteDetection() { if (comparePointTransform == null) return false; var result = false; var axisIndex = (int)axis; var comparePoint = comparePointTransform.position; var pointA = Vector3.zero; var pointB = Vector3.zero; if (enableMatrix) { comparePoint = transform.InverseTransformPoint(comparePoint); pointA[axisIndex] -= height - radius; pointB[axisIndex] += height - radius; } else { pointA = transform.position; pointB = transform.position; pointA[axisIndex] -= height - radius; pointB[axisIndex] += height - radius; } if (comparePoint[axisIndex] < pointA[axisIndex]) { if (Vector3.Distance(comparePoint, pointA) <= radius) { result = true; } } else if (comparePoint[axisIndex] > pointB[axisIndex]) { if (Vector3.Distance(comparePoint, pointB) <= radius) { result = true; } } else { var tmpPos = enableMatrix ? Vector3.zero : transform.position; tmpPos[axisIndex] = comparePoint[axisIndex]; if (Vector3.Distance(comparePoint, tmpPos) <= radius) { result = true; } } return result; } void OnDrawGizmos() { var color = Color.blue; if (ExecuteDetection()) { color = Color.red; } var axisIndex = (int)axis; var pos1 = Vector3.zero; var pos2 = Vector3.zero; if (enableMatrix) { Gizmos.matrix = transform.localToWorldMatrix; pos1[axisIndex] -= height; pos2[axisIndex] += height; } else { pos1 = transform.position; pos2 = transform.position; pos1[axisIndex] -= height; pos2[axisIndex] += height; } DebugExtension.DrawCapsule(pos1, pos2, color, radius); } }
绘制胶囊体使用DebugExtension插件,在资源商店可以免费下载