Unity MCP 的 manage_physics 工具:21 个 Action 掌控 2D/3D 物理世界的完整指南
2026/9/14 7:06:19 网站建设 项目流程

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说明
Settingspingget_settingsset_settings健康检查、读取/写入物理项目设置(重力、求解器迭代、阈值等)
Collision Matrixget_collision_matrixset_collision_matrix读取/配置逐层碰撞矩阵
Materialscreate_physics_materialconfigure_physics_materialassign_physics_material创建、修改、为 Collider 指定物理材质
Jointsadd_jointconfigure_jointremove_joint添加/配置/移除关节(铰链、弹簧、固定、可配置等)
Queriesraycastraycast_alllinecastshapecastoverlap各类物理查询
Forcesapply_force施力、扭矩、力-位置、爆炸力,支持 3D/2D 全部 ForceMode
Rigidbodyget_rigidbodyconfigure_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/gravity2d:3D 与 2D 当前重力向量
  • simulationMode:物理模拟模式(FixedUpdate / Update / Script)
  • defaultSolverIterationsdefaultSolverVelocityIterations:求解器迭代次数
  • bounceThresholdsleepThresholddefaultContactOffset:碰撞阈值与接触偏移
  • queriesHitTriggers:查询是否命中 Trigger

2.2 get_settings —— 按维度读取项目设置

通过dimension"3d"默认 /"2d")参数区分读取路径。3D 分支额外返回defaultMaxAngularSpeedqueriesHitBackfacesautoSyncTransforms;2D 分支返回velocityIterationspositionIterationsqueriesStartInColliderscallbacksOnDisable等。非法维度会返回Invalid dimension错误(PhysicsSettingsOps.cs)。

2.3 set_settings —— 写入物理设置

set_settings需要settings键值对象(非空),且先整体校验、再逐项应用,避免部分写入。3D 可写键集合(源码中全部转为小写比较,见 PhysicsSettingsOps.cs):

类型说明
gravityfloat[3]重力向量
defaultContactOffsetfloat默认接触偏移
sleepThresholdfloat休眠阈值
defaultSolverIterationsint求解器迭代次数
defaultSolverVelocityIterationsint速度求解器迭代次数
bounceThresholdfloat反弹阈值
defaultMaxAngularSpeedfloat最大角速度
queriesHitTriggersbool查询命中 Trigger
queriesHitBackfacesbool查询命中背面
simulationModestringFixedUpdate / Update / Script
autoSyncTransformsbool自动同步 Transform

2D 可写键为gravity(float[2])、velocityIterationspositionIterationsqueriesHitTriggersqueriesStartInColliderscallbacksOnDisableautoSyncTransforms(PhysicsSettingsOps.cs)。

值得注意的实现细节:写入完成后会调用EditorUtility.SetDirty标记ProjectSettings/DynamicsManager.asset(3D)或ProjectSettings/Physics2DSettings.asset(2D),确保修改在项目中持久化(PhysicsSettingsOps.cs);simulationModeautoSyncTransforms等 API 在不同 Unity 版本中可用性不同,因此通过UnityPhysicsCompat兼容层处理(TrySetPhysicsSimulationMode/TrySetPhysicsAutoSyncTransforms)。

三、Collision Matrix:逐层碰撞矩阵

get_collision_matrix读取各 Layer 之间的碰撞开关;set_collision_matrix通过layer_alayer_b(层名或索引)与collide(布尔)启用/禁用任意两个 Layer 的碰撞。其底层对应UnityEngine.Physics.GetIgnoreLayerCollision / SetIgnoreLayerCollision,在validate的"碰撞矩阵"检查中同样用到了GetIgnoreLayerCollision来判断所有已命名 Layer 是否仍处于全碰撞状态(见下文 Validation 章节)。

四、Materials:物理材质完整生命周期

4.1 create_physics_material

创建PhysicMaterial(3D)或PhysicsMaterial2D(2D)资产,默认输出目录为Assets/Physics Materials(可用path覆盖,且必须位于Assets/下,目录不存在会自动创建,见 PhysicsMaterialOps.cs)。3D 材质参数:

  • dynamic_friction(默认 0.6)、static_friction(默认 0.6)、bounciness(默认 0)
  • friction_combine/bounce_combineAverageMinimumMultiplyMaximum

2D 材质仅支持friction(默认 0.4)与bounciness。资产扩展名分别为.physicMaterial.physicsMaterial2D,创建时若路径冲突会返回错误并提示改用configure_physics_material

4.2 configure_physics_material

通过path+properties键值对象修改已有材质。3D 合法属性键为dynamicFrictionstaticFrictionbouncinessfrictionCombinebounceCombine;2D 为frictionbounciness。与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 支持的关节类型

  • 3Dfixed(FixedJoint)、hinge(HingeJoint)、spring(SpringJoint)、character(CharacterJoint)、configurable(ConfigurableJoint)
  • 2Ddistancefixedfrictionhingerelativesliderspringtargetwheel

类型映射定义在 JointOps.cs。

5.2 add_joint

需要targetjoint_type。维度自动检测规则:目标同时有 Rigidbody 与 Rigidbody2D 时默认优先 3D;显式传入dimension可覆盖,但若目标缺少对应刚体组件会直接报错(JointOps.cs)。connected_body可选,且会在变更场景之前先验证连接体存在且具备对应刚体组件。添加前会先校验目标已有 Rigidbody/Rigidbody2D("Add one before adding a joint"),并通过Undo.AddComponent保证可撤销。

5.3 configure_joint

支持三类结构化配置块加一类通用透传:

  • motor{targetVelocity, force, freeSpin}(仅 HingeJoint,设置后自动useMotor = true
  • limits{min, max, bounciness}(仅 HingeJoint,自动useLimits = true
  • spring{spring, damper, targetPosition}(HingeJoint / SpringJoint)
  • drive{xDrive: {positionSpring, positionDamper, maximumForce}}(仅 ConfigurableJoint)
  • properties:任意公开属性/字段,通过反射写入并做类型转换(float/int/bool/string/Vector2/Vector3)

若目标上存在多个关节而未指定joint_type,会返回提示要求明确指定类型(JointOps.cs)。

5.4 remove_joint

remove_jointjoint_type移除指定类型(可配component_index精确定位),省略joint_type则移除该对象上的全部 3D 与 2D 关节。使用Undo.DestroyObjectImmediate删除并返回removedCount

六、Queries:五种物理查询

查询类 Action 全部支持 2D/3D,返回统一结构(hitpointnormaldistancegameObjectinstanceIDcollider_type),实现见 PhysicsQueryOps.cs。

Action说明关键参数
raycast单命中射线origindirectionmax_distance(默认 Infinity)、layer_maskquery_trigger_interaction
raycast_all多命中射线,结果按距离升序排序同 raycast,返回hit_count+hits
linecast两点之间线段是否被阻挡startend
shapecast形状(球/盒/胶囊)沿方向投射shapeorigindirectionsizepoint1/point2heightcapsule_direction
overlap在位置处找形状内所有 Collidershapepositionsize

各查询的参数细节:

  • 坐标数组:3D 用[x,y,z],2D 用[x,y]
  • size的多态解析sphere/circle用单个 float 半径;box[halfX,halfY,halfZ](3D)或[width,height](2D);capsule在 3D 用{radius, height, direction}(direction:0=X、1=Y、2=Z),在 2D 用{width, height, direction}(direction:vertical/horizontal)。
  • layer_mask:支持整数掩码或 Layer 名称,空值表示全部 Layer(~0);名称解析失败会抛出Unknown layer name异常(PhysicsQueryOps.cs)。
  • query_trigger_interactionUseGlobal(默认)、IgnoreCollide
  • 每次查询前都会调用Physics.SyncTransforms()/Physics2D.SyncTransforms(),保证编辑模式下 Transform 修改先同步到物理引擎,查询结果与场景实际一致。

七、Forces:力的施加

apply_force是功能最丰富的单 Action(PhysicsForceOps.cs),支持普通力与爆炸力两种force_type

普通力(normal):至少提供forcetorque之一,可同时施加两者;提供position时改用AddForceAtPosition施力于指定点。force_mode

  • 3D:ForceImpulseAccelerationVelocityChange(对应全部ForceMode
  • 2D:仅ForceImpulseForceMode2D

爆炸力(explosion):仅 3D,需要explosion_forceexplosion_positionexplosion_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.cs),3D 返回:masslinearDampingangularDampinguseGravityisKinematicpositionrotation(四元数)、velocityangularVelocityinterpolationcollisionDetectionModeconstraintsisSleepingcenterOfMassmaxAngularVelocity(Unity 6 下还有maxLinearVelocity)。2D 返回massgravityScaledragangularDragbodyTypesimulated等。

兼容性细节:源码中drag/angularDragvelocity/linearVelocity通过#if UNITY_6000_0_OR_NEWER条件编译——Unity 6 之后 Rigidbody 的drag重命名为linearDampingangularDrag重命名为angularDampingvelocity重命名为linearVelocity,该工具已同时兼容两代 API。

8.2 configure_rigidbody

通过target+properties键值对象配置。3D 合法键:massdrag(或linearDamping)、angularDrag(或angularDamping)、useGravityisKinematicinterpolationcollisionDetectionModeconstraints;2D 合法键:massgravityScaledragangularDragbodyTypesimulatedcollisionDetectionModeconstraints。键名校验集合见 PhysicsRigidbodyOps.cs,非法键在应用前即被拒绝。

九、Validation:场景物理体检

validate是对整个场景(或单个target)的物理健康扫描(PhysicsValidationOps.cs)。dimension可选"3d""2d"或默认"both"

9.1 7 类检查项

类别检查逻辑
non_convex_mesh非 Kinematic 刚体上的 MeshCollider 未勾选 Convex
missing_rigidbody非静态对象有 Collider 但无 Rigidbody
non_uniform_scale带 Collider 的对象存在非均匀缩放(会降低物理性能)
fast_object_discrete名称含 bullet/projectile/fast 的对象仍使用 Discrete 碰撞检测,建议 ContinuousDynamic
missing_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 isn't moved at runtime")。物理材质缺失类告警同样标记为[Info]

9.3 分页与汇总

大场景可能产生成百上千条告警,因此默认每页 50 条(page_size可调,cursor为偏移量),响应包含next_cursor(无下一页时为 null),且无论在哪一页,summary字段都会返回完整的 7 类计数(PhysicsValidationOps.cs)。同时返回warning_countobjects_scanned

十、Simulation:编辑模式模拟步进

simulate_step允许在编辑模式下手动推进物理世界(PhysicsSimulationOps.cs):

  • steps:1–100,超出自动 Clamp
  • step_size:秒,默认Time.fixedDeltaTime
  • target:可选,过滤只上报指定对象;省略则上报场景中活跃(非 Kinematic/非 Static、未休眠)的刚体,上限 50 个

实现细节:3D 路径会先暂存当前simulationMode,若不为Script则切换为Script模式,逐帧调用Physics.Simulate(stepSize),并在finally中恢复原模式——保证不会污染用户项目的模拟设置。步进完成后统一采集所有活跃刚体的positionvelocityangularVelocity(2D 还有angularVelocity标量),返回steps_executedstep_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" dynamicFriction=0.5 bounciness=0.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.targetVelocity=90 motor.force=100 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" mass=2 useGravity=false # 校验与模拟 mcp-for-unity physics validate mcp-for-unity physics simulate -s 10 --step-size 0.02

CLI 命令通过_coerce_cli_value自动把字符串转换为 bool/int/float("true"/"false" 转布尔,含.转浮点,否则转整数),向量类参数用逗号分隔(如"0,1,0")。输出格式由config.format控制(如 JSON),便于脚本化集成。

十二、架构设计与源码落位

12.1 三层实现

该功能横跨三层,职责清晰:

文件职责
Python MCP 服务Server/src/services/tools/manage_physics.py21-action 的Literal类型定义与参数校验,参数全量透传给 Unity
Python 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 类:

文件负责 Action
PhysicsSettingsOps.csping、get_settings、set_settings
CollisionMatrixOps.csget_collision_matrix、set_collision_matrix
PhysicsMaterialOps.cscreate/configure/assign physics materials
JointOps.csadd_joint、configure_joint、remove_joint
PhysicsQueryOps.csraycast、raycast_all、linecast、shapecast、overlap
PhysicsForceOps.csapply_force
PhysicsRigidbodyOps.csget_rigidbody、configure_rigidbody
PhysicsValidationOps.csvalidate
PhysicsSimulationOps.cssimulate_step

参数解析统一通过ToolParams(ToolParams.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 工具之一。

十四、典型使用场景与提示

  1. AI 驱动的物理调试:先用validate找出问题(非凸网格、缺刚体、非均匀缩放、快物体离散检测、2D/3D 混用),再结合get_settings/set_settings修正项目级参数,用simulate_step验证效果,形成闭环。
  2. 程序化场景搭建create_physics_material+assign_physics_material批量配置材质,add_joint/configure_joint搭建机械结构(门、弹簧、铰链、可配置关节的驱动)。
  3. 查询与反馈raycast/overlap可用于 AI 做"虚拟传感器",判断场景布局是否合理后再执行修改。
  4. 使用限制apply_force无法作用于 Kinematic 刚体;爆炸力仅 3D;simulate_step会临时切换到 Script 模拟模式并在结束时恢复;物理设置写入会落盘到ProjectSettings/DynamicsManager.assetPhysics2DSettings.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),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询