Unity胶囊体的碰撞检测实现
可选是否打开矩阵变换,支持xyz三种朝向

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插件,在资源商店可以免费下载
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
2015-03-31 正则表达式检测注册用户名是否规范