You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity报错:无法将float转换为Vector3,CapsuleCast调用问题求助

Unity Physics.CapsuleCast 参数错误修复

问题根源

你第20行调用Physics.CapsuleCast时参数顺序完全错误,报错“无法将float转为Vector3”是因为第二个参数传了float类型的radius,但这个位置需要的是胶囊的终点位置(Vector3类型)。你之前修改第17行把radius改成Vector3的操作完全没必要,反而会引发新问题。

正确修复方案

Physics.CapsuleCast的常用重载参数顺序是:
Physics.CapsuleCast(Vector3 胶囊起点, Vector3 胶囊终点, float 胶囊半径, Vector3 检测方向, out RaycastHit 碰撞信息, float 最大检测距离, int 层掩码)

按这个顺序调整代码,同时补充胶囊的两个端点定义(可根据你的需求调整偏移方向和距离):

public static class Extensions
{
    private static LayerMask layerMask = LayerMask.GetMask("Default");

    public static bool CapsuleCast(this Rigidbody rigidbody, Vector3 direction)
    {
        if (rigidbody.isKinematic)
        {
            return false;
        }

        float radius = 0.125f;
        float maxDistance = 0.375f;
        // 定义胶囊的两个端点,这里沿Y轴上下偏移,适配角色类胶囊碰撞体的常见结构
        Vector3 capsuleStart = rigidbody.position - Vector3.up * 0.25f;
        Vector3 capsuleEnd = rigidbody.position + Vector3.up * 0.25f;

        RaycastHit hit;
        // 按正确参数顺序调用API,用out接收碰撞结果
        bool hasHit = Physics.CapsuleCast(capsuleStart, capsuleEnd, radius, direction, out hit, maxDistance, layerMask);
        return hasHit && hit.rigidbody != rigidbody;
    }
}

额外说明

  • 变量名Hit改成小写hit,符合C#命名规范
  • 新版Unity中Physics.CapsuleCast需要用out参数传递碰撞信息,旧写法会报错
  • 胶囊端点的偏移方向和距离可以根据你的实际碰撞需求调整,比如如果是水平胶囊,就用Vector3.forward或Vector3.right偏移

内容的提问来源于stack exchange,提问作者SSENiOR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:01:17