
Unity MCP 的 manage_physics 工具21 个 Action 掌控 2D/3D 物理世界的完整指南【免费下载链接】unity-mcpUnity MCP acts as a bridge between AI assistants and your Unity Editor. Give your LLM tools to manage assets, control scenes, edit scripts, and automate tasks within Unity.项目地址: https://gitcode.com/GitHub_Trending/un/unity-mcp导读manage_physics是 Unity MCP 为 AI 助手提供的物理系统控制工具它把 Unity 的 3D 与 2D 物理能力封装成21 个动作、9 大类别的 MCP 接口从项目级物理设置重力、求解器迭代次数、碰撞矩阵到材质、关节、射线查询、力的施加、Rigidbody 状态读写再到场景物理问题校验与编辑模式下的模拟步进AI 可以在不改写任何 C# 代码的前提下通过自然语言驱动 Unity 完成完整的物理调试与场景搭建工作流。本文基于仓库架构文档 website/docs/architecture/manage-physics.md 展开并结合 C# Editor 实现、Python MCP 服务与 CLI 命令的源码细节帮助你彻底理解每个 Action 的参数、调用链与底层原理。一、功能总览21 个 Action 与 9 大类别manage_physics覆盖了 Unity 物理系统的完整操作面文档将其划分为 9 个类别类别Action说明Settingsping、get_settings、set_settings健康检查、读取/写入物理项目设置重力、求解器迭代、阈值等Collision Matrixget_collision_matrix、set_collision_matrix读取/配置逐层碰撞矩阵Materialscreate_physics_material、configure_physics_material、assign_physics_material创建、修改、为 Collider 指定物理材质Jointsadd_joint、configure_joint、remove_joint添加/配置/移除关节铰链、弹簧、固定、可配置等Queriesraycast、raycast_all、linecast、shapecast、overlap各类物理查询Forcesapply_force施力、扭矩、力-位置、爆炸力支持 3D/2D 全部 ForceModeRigidbodyget_rigidbody、configure_rigidbody读取完整刚体状态、配置刚体属性Validationvalidate场景物理问题扫描分页 分类汇总Simulationsimulate_step编辑模式下步进物理模拟1–100 步从 Python 服务端定义看这 21 个 action 被编码为Literal类型联合见 Server/src/services/tools/manage_physics.py。所有 action 共用同一个manage_physicsMCP 工具入口通过action参数分派并在 C# 侧由 ManagePhysics.cs 的switch分发到各自的 Ops 类。二、Settings物理系统设置的全读写2.1 ping —— 健康检查与状态快照ping返回重力、求解器设置与模拟模式是 AI 接入物理工作流的第一步。源码实现于 PhysicsSettingsOps.cs返回内容包括gravity3d/gravity2d3D 与 2D 当前重力向量simulationMode物理模拟模式FixedUpdate / Update / ScriptdefaultSolverIterations、defaultSolverVelocityIterations求解器迭代次数bounceThreshold、sleepThreshold、defaultContactOffset碰撞阈值与接触偏移queriesHitTriggers查询是否命中 Trigger2.2 get_settings —— 按维度读取项目设置通过dimension3d默认 /2d参数区分读取路径。3D 分支额外返回defaultMaxAngularSpeed、queriesHitBackfaces、autoSyncTransforms2D 分支返回velocityIterations、positionIterations、queriesStartInColliders、callbacksOnDisable等。非法维度会返回Invalid dimension错误PhysicsSettingsOps.cs。2.3 set_settings —— 写入物理设置set_settings需要settings键值对象非空且先整体校验、再逐项应用避免部分写入。3D 可写键集合源码中全部转为小写比较见 PhysicsSettingsOps.cs键类型说明gravityfloat[3]重力向量defaultContactOffsetfloat默认接触偏移sleepThresholdfloat休眠阈值defaultSolverIterationsint求解器迭代次数defaultSolverVelocityIterationsint速度求解器迭代次数bounceThresholdfloat反弹阈值defaultMaxAngularSpeedfloat最大角速度queriesHitTriggersbool查询命中 TriggerqueriesHitBackfacesbool查询命中背面simulationModestringFixedUpdate / Update / ScriptautoSyncTransformsbool自动同步 Transform2D 可写键为gravityfloat[2]、velocityIterations、positionIterations、queriesHitTriggers、queriesStartInColliders、callbacksOnDisable、autoSyncTransformsPhysicsSettingsOps.cs。值得注意的实现细节写入完成后会调用EditorUtility.SetDirty标记ProjectSettings/DynamicsManager.asset3D或ProjectSettings/Physics2DSettings.asset2D确保修改在项目中持久化PhysicsSettingsOps.cssimulationMode与autoSyncTransforms等 API 在不同 Unity 版本中可用性不同因此通过UnityPhysicsCompat兼容层处理TrySetPhysicsSimulationMode/TrySetPhysicsAutoSyncTransforms。三、Collision Matrix逐层碰撞矩阵get_collision_matrix读取各 Layer 之间的碰撞开关set_collision_matrix通过layer_a、layer_b层名或索引与collide布尔启用/禁用任意两个 Layer 的碰撞。其底层对应UnityEngine.Physics.GetIgnoreLayerCollision / SetIgnoreLayerCollision在validate的碰撞矩阵检查中同样用到了GetIgnoreLayerCollision来判断所有已命名 Layer 是否仍处于全碰撞状态见下文 Validation 章节。四、Materials物理材质完整生命周期4.1 create_physics_material创建PhysicMaterial3D或PhysicsMaterial2D2D资产默认输出目录为Assets/Physics Materials可用path覆盖且必须位于Assets/下目录不存在会自动创建见 PhysicsMaterialOps.cs。3D 材质参数dynamic_friction默认 0.6、static_friction默认 0.6、bounciness默认 0friction_combine/bounce_combineAverage、Minimum、Multiply、Maximum2D 材质仅支持friction默认 0.4与bounciness。资产扩展名分别为.physicMaterial与.physicsMaterial2D创建时若路径冲突会返回错误并提示改用configure_physics_material。4.2 configure_physics_material通过pathproperties键值对象修改已有材质。3D 合法属性键为dynamicFriction、staticFriction、bounciness、frictionCombine、bounceCombine2D 为friction、bounciness。与set_settings相同采用先整体校验键名、再逐项应用的策略非法键直接报错PhysicsMaterialOps.cs。所有修改均包裹Undo.RecordObject以支持编辑器撤销。4.3 assign_physics_material将材质资产赋给目标 GameObject 上的 Collider。参数material_path指向资产collider_type可选指定 Collider 子类型component_index可选同一类型存在多个组件时用 0 起始索引选择。实现会先尝试按 3DPhysicsMaterial加载再按 2DPhysicsMaterial2D加载随后分别匹配 3D/2D Collider若指定了component_index但越界会返回实际组件数量的错误提示PhysicsMaterialOps.cs。五、Joints关节的添加、配置与移除5.1 支持的关节类型3DfixedFixedJoint、hingeHingeJoint、springSpringJoint、characterCharacterJoint、configurableConfigurableJoint2Ddistance、fixed、friction、hinge、relative、slider、spring、target、wheel类型映射定义在 JointOps.cs。5.2 add_joint需要target与joint_type。维度自动检测规则目标同时有 Rigidbody 与 Rigidbody2D 时默认优先 3D显式传入dimension可覆盖但若目标缺少对应刚体组件会直接报错JointOps.cs。connected_body可选且会在变更场景之前先验证连接体存在且具备对应刚体组件。添加前会先校验目标已有 Rigidbody/Rigidbody2DAdd one before adding a joint并通过Undo.AddComponent保证可撤销。5.3 configure_joint支持三类结构化配置块加一类通用透传motor{targetVelocity, force, freeSpin}仅 HingeJoint设置后自动useMotor truelimits{min, max, bounciness}仅 HingeJoint自动useLimits truespring{spring, damper, targetPosition}HingeJoint / SpringJointdrive{xDrive: {positionSpring, positionDamper, maximumForce}}仅 ConfigurableJointproperties任意公开属性/字段通过反射写入并做类型转换float/int/bool/string/Vector2/Vector3若目标上存在多个关节而未指定joint_type会返回提示要求明确指定类型JointOps.cs。5.4 remove_jointremove_joint按joint_type移除指定类型可配component_index精确定位省略joint_type则移除该对象上的全部 3D 与 2D 关节。使用Undo.DestroyObjectImmediate删除并返回removedCount。六、Queries五种物理查询查询类 Action 全部支持 2D/3D返回统一结构hit、point、normal、distance、gameObject、instanceID、collider_type实现见 PhysicsQueryOps.cs。Action说明关键参数raycast单命中射线origin、direction、max_distance默认 Infinity、layer_mask、query_trigger_interactionraycast_all多命中射线结果按距离升序排序同 raycast返回hit_counthitslinecast两点之间线段是否被阻挡start、endshapecast形状球/盒/胶囊沿方向投射shape、origin、direction、size、point1/point2、height、capsule_directionoverlap在位置处找形状内所有 Collidershape、position、size各查询的参数细节坐标数组3D 用[x,y,z]2D 用[x,y]。size的多态解析sphere/circle用单个 float 半径box用[halfX,halfY,halfZ]3D或[width,height]2Dcapsule在 3D 用{radius, height, direction}direction0X、1Y、2Z在 2D 用{width, height, direction}directionvertical/horizontal。layer_mask支持整数掩码或 Layer 名称空值表示全部 Layer~0名称解析失败会抛出Unknown layer name异常PhysicsQueryOps.cs。query_trigger_interactionUseGlobal默认、Ignore、Collide。每次查询前都会调用Physics.SyncTransforms()/Physics2D.SyncTransforms()保证编辑模式下 Transform 修改先同步到物理引擎查询结果与场景实际一致。七、Forces力的施加apply_force是功能最丰富的单 ActionPhysicsForceOps.cs支持普通力与爆炸力两种force_type。普通力normal至少提供force或torque之一可同时施加两者提供position时改用AddForceAtPosition施力于指定点。force_mode3DForce、Impulse、Acceleration、VelocityChange对应全部ForceMode2D仅Force、ImpulseForceMode2D爆炸力explosion仅 3D需要explosion_force、explosion_position、explosion_radius可选upwards_modifier映射Rigidbody.AddExplosionForce。实施前会校验目标必须存在对应刚体、且不能是 Kinematic返回 Cannot apply force to kinematic Rigidbody维度默认按组件自动检测同时存在时 3D 优先。所有施加过的值都会回显在响应data中force/torque 向量、force_mode、force_type、dimension便于 AI 确认行为。八、Rigidbody状态读取与配置8.1 get_rigidbody读取完整刚体状态PhysicsRigidbodyOps.cs3D 返回mass、linearDamping、angularDamping、useGravity、isKinematic、position、rotation四元数、velocity、angularVelocity、interpolation、collisionDetectionMode、constraints、isSleeping、centerOfMass、maxAngularVelocityUnity 6 下还有maxLinearVelocity。2D 返回mass、gravityScale、drag、angularDrag、bodyType、simulated等。兼容性细节源码中drag/angularDrag与velocity/linearVelocity通过#if UNITY_6000_0_OR_NEWER条件编译——Unity 6 之后 Rigidbody 的drag重命名为linearDamping、angularDrag重命名为angularDampingvelocity重命名为linearVelocity该工具已同时兼容两代 API。8.2 configure_rigidbody通过targetproperties键值对象配置。3D 合法键mass、drag或linearDamping、angularDrag或angularDamping、useGravity、isKinematic、interpolation、collisionDetectionMode、constraints2D 合法键mass、gravityScale、drag、angularDrag、bodyType、simulated、collisionDetectionMode、constraints。键名校验集合见 PhysicsRigidbodyOps.cs非法键在应用前即被拒绝。九、Validation场景物理体检validate是对整个场景或单个target的物理健康扫描PhysicsValidationOps.cs。dimension可选3d、2d或默认both。9.1 7 类检查项类别检查逻辑non_convex_mesh非 Kinematic 刚体上的 MeshCollider 未勾选 Convexmissing_rigidbody非静态对象有 Collider 但无 Rigidbodynon_uniform_scale带 Collider 的对象存在非均匀缩放会降低物理性能fast_object_discrete名称含 bullet/projectile/fast 的对象仍使用 Discrete 碰撞检测建议 ContinuousDynamicmissing_physics_materialCollider 未指定物理材质默认值collision_matrix场景级检查所有已命名 Layer 互相全部碰撞时提示禁用无用层对mixed_2d_3d同一对象同时混用 2D 与 3D 物理组件9.2 智能告警级别Collider without Rigidbody 只有在该对象或其父级见HasAnimatorInParent带Animator、暗示运行时会被移动时才升级为正式警告Moving it via Transform causes broadphase rebuild every frame否则降级为[Info]This is fine if the object isnt moved at runtime。物理材质缺失类告警同样标记为[Info]。9.3 分页与汇总大场景可能产生成百上千条告警因此默认每页 50 条page_size可调cursor为偏移量响应包含next_cursor无下一页时为 null且无论在哪一页summary字段都会返回完整的 7 类计数PhysicsValidationOps.cs。同时返回warning_count与objects_scanned。十、Simulation编辑模式模拟步进simulate_step允许在编辑模式下手动推进物理世界PhysicsSimulationOps.cssteps1–100超出自动 Clampstep_size秒默认Time.fixedDeltaTimetarget可选过滤只上报指定对象省略则上报场景中活跃非 Kinematic/非 Static、未休眠的刚体上限 50 个实现细节3D 路径会先暂存当前simulationMode若不为Script则切换为Script模式逐帧调用Physics.Simulate(stepSize)并在finally中恢复原模式——保证不会污染用户项目的模拟设置。步进完成后统一采集所有活跃刚体的position、velocity、angularVelocity2D 还有angularVelocity标量返回steps_executed、step_size与刚体状态数组。十一、CLI无需 MCP 客户端的命令行入口Python CLI 提供与 MCP 工具一一对应的子命令Server/src/cli/commands/physics.py便于无图形客户端的场景直接使用# 健康检查与设置 mcp-for-unity physics ping mcp-for-unity physics get-settings -d 3d mcp-for-unity physics set-settings -d 3d gravity 0,-9.81,0 mcp-for-unity physics set-settings -d 2d velocityIterations 10 # 碰撞矩阵 mcp-for-unity physics get-collision-matrix mcp-for-unity physics set-collision-matrix Player Enemy --ignore # 材质 mcp-for-unity physics create-material -n Bouncy -p Assets/Physics Materials -b 0.8 mcp-for-unity physics configure-material -p Assets/Physics Materials/Bouncy.physicMaterial dynamicFriction0.5 bounciness0.9 mcp-for-unity physics assign-material -t Ball -m Assets/Physics Materials/Bouncy.physicMaterial # 关节 mcp-for-unity physics add-joint -t Door -j hinge --connected-body Frame mcp-for-unity physics configure-joint -t Door -j hinge motor.targetVelocity90 motor.force100 mcp-for-unity physics remove-joint -t Door -j hinge # 查询 mcp-for-unity physics raycast -o 0,1,0 -d 0,-1,0 --max-distance 100 mcp-for-unity physics raycast-all -o 0,1,0 -d 0,-1,0 mcp-for-unity physics linecast -s 0,0,0 -e 10,0,0 mcp-for-unity physics shapecast -s sphere -o 0,1,0 -d 0,-1,0 --size 0.5 mcp-for-unity physics overlap -s sphere -p 0,0,0 --size 2 # 力与刚体 mcp-for-unity physics apply-force -t Player -f 0,10,0 --force-mode Impulse mcp-for-unity physics get-rigidbody Player mcp-for-unity physics configure-rigidbody -t Player mass2 useGravityfalse # 校验与模拟 mcp-for-unity physics validate mcp-for-unity physics simulate -s 10 --step-size 0.02CLI 命令通过_coerce_cli_value自动把字符串转换为 bool/int/floattrue/false 转布尔含.转浮点否则转整数向量类参数用逗号分隔如0,1,0。输出格式由config.format控制如 JSON便于脚本化集成。十二、架构设计与源码落位12.1 三层实现该功能横跨三层职责清晰层文件职责Python MCP 服务Server/src/services/tools/manage_physics.py21-action 的Literal类型定义与参数校验参数全量透传给 UnityPython CLIServer/src/cli/commands/physics.py每个 Action 类别对应的命令行子命令C# EditorMCPForUnity/Editor/Tools/Physics/ 下 10 个文件实际物理 API 调用与响应组装12.2 C# 端模块化设计ManagePhysics.cs以[McpForUnityTool(manage_physics, AutoRegister false, Group core)]注册为 MCP 工具并按 action 分发到 10 个 Ops 类文件负责 ActionPhysicsSettingsOps.csping、get_settings、set_settingsCollisionMatrixOps.csget_collision_matrix、set_collision_matrixPhysicsMaterialOps.cscreate/configure/assign physics materialsJointOps.csadd_joint、configure_joint、remove_jointPhysicsQueryOps.csraycast、raycast_all、linecast、shapecast、overlapPhysicsForceOps.csapply_forcePhysicsRigidbodyOps.csget_rigidbody、configure_rigidbodyPhysicsValidationOps.csvalidatePhysicsSimulationOps.cssimulate_step参数解析统一通过ToolParamsToolParams.cs与ParamCoercion完成目标对象解析统一走GameObjectLookup支持名称/InstanceID配合search_method。12.3 关键设计决策模块化 Ops 类每个物理领域设置、材质、关节、查询、力等独立成类而非单一巨型 handler便于维护与单测。自动维度检测绝大多数 Action 根据目标上 Rigidbody/Rigidbody2D 的存在自动判断 2D/3D同时支持dimension显式覆盖默认冲突时 3D 优先。Unity 版本兼容#if UNITY_6000_0_OR_NEWER处理 API 重命名drag→linearDamping、angularDrag→angularDamping、velocity→linearVelocity兼容层见 UnityPhysicsCompat.cs。validate 分页大场景默认每页 50 条但分类汇总始终返回全部计数避免 AI 因只看一页而误判全局。智能告警级别静态 Collider 无刚体时降级为[Info]除非带 Animator。富响应力/爆炸力回显全部施加值模拟返回刚体状态校验返回分类统计让 AI 每次操作后都能拿到可核对的证据。十三、测试保障该功能自带完整测试体系Python 单元测试Server/tests/test_manage_physics.py 包含 19 个测试用例覆盖 action 转发、参数校验与维度处理。Unity EditMode 测试套件TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManagePhysicsTests.cs 为约 973 行的 EditMode 测试验证 C# 端各 Ops 类的真实行为。从统计看该功能整体净增 5,985 / 净减 −2,965 行新增 10 个 C# 文件含 .meta、3 个 Python 文件提供 21 个 Action 与 19 个 Python 测试是当前仓库中覆盖面最广的 MCP 工具之一。十四、典型使用场景与提示AI 驱动的物理调试先用validate找出问题非凸网格、缺刚体、非均匀缩放、快物体离散检测、2D/3D 混用再结合get_settings/set_settings修正项目级参数用simulate_step验证效果形成闭环。程序化场景搭建create_physics_materialassign_physics_material批量配置材质add_joint/configure_joint搭建机械结构门、弹簧、铰链、可配置关节的驱动。查询与反馈raycast/overlap可用于 AI 做虚拟传感器判断场景布局是否合理后再执行修改。使用限制apply_force无法作用于 Kinematic 刚体爆炸力仅 3Dsimulate_step会临时切换到 Script 模拟模式并在结束时恢复物理设置写入会落盘到ProjectSettings/DynamicsManager.asset或Physics2DSettings.asset修改前建议先get_settings确认当前值。通过本文档与仓库源码你可以将manage_physics无缝接入 AI 工作流让 LLM 以统一的 21 个 Action 完成 Unity 2D/3D 物理系统的读取、配置、查询、施力、校验与模拟——这正是 Unity MCP 作为 AI 与编辑器之间桥梁的核心价值所在。【免费下载链接】unity-mcpUnity MCP acts as a bridge between AI assistants and your Unity Editor. Give your LLM tools to manage assets, control scenes, edit scripts, and automate tasks within Unity.项目地址: https://gitcode.com/GitHub_Trending/un/unity-mcp创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考