godot-physics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGodot Physics (4.x, 2D + 3D)
Godot 物理系统(4.x版本,2D + 3D)
Pick the right physics body, wire up collision layers/masks, detect overlaps, and cast
rays. Concepts apply to both 2D and 3D (swap the / suffix). Targets
Godot 4.3+.
2D3D选择合适的物理体,配置碰撞层与掩码,检测重叠并进行射线投射。相关概念同时适用于2D和3D场景(只需替换/后缀即可)。适配**Godot 4.3+**版本。
2D3DWhen to use
适用场景
- Use when choosing between body types, setting collision layers/masks so the right
things collide, detecting overlaps (triggers, hurtboxes) with , applying forces/impulses to a
Area, or casting rays for line-of-sight/ground checks.RigidBody
When not to use: kinematic character controllers () →
; tile collision setup → ; tuning the feel of physics
(timestep, mass, jitter) → .
move_and_slidegodot-2d-movementgodot-tilemapphysics-tuning- 适用于选择物理体类型、设置碰撞层/掩码以实现正确的碰撞交互、通过检测重叠(触发器、伤害判定框)、向
Area施加力/冲量,或通过射线投射实现视线检测/地面检测的场景。RigidBody
不适用场景: 运动学角色控制器()→ 参考;瓦片碰撞设置 → 参考;物理手感调优(时间步长、质量、抖动)→ 参考。
move_and_slidegodot-2d-movementgodot-tilemapphysics-tuningCore workflow
核心工作流程
- Choose the body type:
- — never moves (floors, walls). Collides, no simulation.
StaticBody - — fully simulated (gravity, forces, bouncing). Don't set its
RigidBodydirectly; apply forces/impulses or setposition.linear_velocity - — script-driven kinematic (see
CharacterBody).godot-2d-movement - — detects overlaps and can apply gravity/damping; no solid collision. Every body needs a
Area(orCollisionShape) child.CollisionPolygon
- Configure layers and masks. A body is on its layers and scans for its masks. Two bodies interact only if one's layer is in the other's mask. Name layers in Project Settings > Layer Names for clarity.
- Detect overlaps with signals (
Area,body_entered).area_entered - Drive RigidBodies with forces/impulses, or override for full control.
_integrate_forces - Cast rays with a node (polled each frame) or a one-shot space-state query from code.
RayCast2D/3D
- 选择物理体类型:
- — 静止不动(地板、墙体)。可发生碰撞,但不参与物理模拟。
StaticBody - — 完全受物理模拟(重力、外力、弹跳)。请勿直接设置其
RigidBody;应施加力/冲量或设置position。linear_velocity - — 由脚本驱动的运动学体(参考
CharacterBody)。godot-2d-movement - — 检测重叠区域,可施加重力/阻尼;无实体碰撞。 每个物理体都需要一个
Area(或CollisionShape)子节点。CollisionPolygon
- 配置碰撞层与掩码。物理体属于自身的碰撞层,并会扫描自身碰撞掩码中的层。只有当一个物体的碰撞层在另一个物体的碰撞掩码中时,两者才会产生交互。可在项目设置 > 层名称中为碰撞层命名,提升可读性。
- 通过信号检测重叠(
Area、body_entered)。area_entered - 通过力/冲量驱动RigidBody,或重写实现完全控制。
_integrate_forces - 射线投射:使用节点(每帧轮询),或通过代码执行一次性空间状态查询。
RayCast2D/3D
Patterns
实践模式
1. Collision layers vs masks (set from code)
1. 碰撞层与掩码(通过代码设置)
gdscript
undefinedgdscript
undefinedPlayer is on layer 1, scans layers 2 (walls) and 3 (enemies).
玩家位于第1层,检测第2层(墙体)和第3层(敌人)的对象。
func _ready() -> void:
set_collision_layer_value(1, true) # I am on layer 1
set_collision_mask_value(2, true) # I collide with things on layer 2
set_collision_mask_value(3, true) # ...and layer 3
# Bit-field forms also exist: collision_layer = 1; collision_mask = 0b110
undefinedfunc _ready() -> void:
set_collision_layer_value(1, true) # 我属于第1层
set_collision_mask_value(2, true) # 我与第2层的物体碰撞
set_collision_mask_value(3, true) # ...同时与第3层的物体碰撞
# 也支持位域形式:collision_layer = 1; collision_mask = 0b110
undefined2. Area2D as a trigger / hurtbox
2. 将Area2D用作触发器 / 伤害判定框
gdscript
extends Area2D # e.g. a damage zone
func _ready() -> void:
body_entered.connect(_on_body_entered)
area_entered.connect(_on_area_entered)
func _on_body_entered(body: Node2D) -> void:
if body.has_method("take_damage"):
body.take_damage(10)
func _on_area_entered(area: Area2D) -> void:
print("Overlapped area: ", area.name)gdscript
extends Area2D # 例如:一个伤害区域
func _ready() -> void:
body_entered.connect(_on_body_entered)
area_entered.connect(_on_area_entered)
func _on_body_entered(body: Node2D) -> void:
if body.has_method("take_damage"):
body.take_damage(10)
func _on_area_entered(area: Area2D) -> void:
print("重叠区域:", area.name)3. Applying force and impulse to a RigidBody3D
3. 向RigidBody3D施加力与冲量
gdscript
extends RigidBody3D
func push(direction: Vector3) -> void:
apply_central_impulse(direction * 8.0) # instantaneous velocity change
func _physics_process(_delta: float) -> void:
apply_central_force(Vector3.FORWARD * 4.0) # continuous force (per tick)
# Never set `position` on a RigidBody to move it; use forces/impulses or
# set linear_velocity. Use freeze=true if you must hold it in place.gdscript
extends RigidBody3D
func push(direction: Vector3) -> void:
apply_central_impulse(direction * 8.0) # 瞬时速度变化
func _physics_process(_delta: float) -> void:
apply_central_force(Vector3.FORWARD * 4.0) # 持续力(每物理帧)
# 切勿通过设置`position`移动RigidBody;应使用力/冲量或设置linear_velocity。若需固定位置,可设置freeze=true。4. Raycast two ways
4. 两种射线投射方式
gdscript
undefinedgdscript
undefinedA) RayCast2D node: enable it, then poll after physics has updated.
A) RayCast2D节点:启用后,在物理更新完成后进行轮询。
@onready var ray: RayCast2D = $RayCast2D # set target_position in the editor
func _physics_process(_delta: float) -> void:
if ray.is_colliding():
var hit := ray.get_collider()
var point := ray.get_collision_point()
@onready var ray: RayCast2D = $RayCast2D # 在编辑器中设置target_position
func _physics_process(_delta: float) -> void:
if ray.is_colliding():
var hit := ray.get_collider()
var point := ray.get_collision_point()
B) One-shot query from code (no node needed).
B) 通过代码执行一次性查询(无需节点)。
func ground_under(global_from: Vector2) -> Dictionary:
var space := get_world_2d().direct_space_state
var query := PhysicsRayQueryParameters2D.create(global_from, global_from + Vector2(0, 64))
query.collision_mask = 1 # only layer 1
return space.intersect_ray(query) # {} if nothing hit, else collider/position/normal
undefinedfunc ground_under(global_from: Vector2) -> Dictionary:
var space := get_world_2d().direct_space_state
var query := PhysicsRayQueryParameters2D.create(global_from, global_from + Vector2(0, 64))
query.collision_mask = 1 # 仅检测第1层
return space.intersect_ray(query) # 未命中返回{},命中则返回collider/position/normal等数据
undefinedPitfalls
常见陷阱
- Layer vs mask confusion is the #1 bug. Layer = "what I am"; mask = "what I look for". For A to detect B, B's layer must be in A's mask. Detection can be one-directional.
- Moving a RigidBody by fights the solver and causes tunneling/jitter. Use impulses/forces, set
position, orlinear_velocityit. To teleport, set position and zero the velocities insidefreeze._integrate_forces - doesn't fire when neither monitoring nor monitorable is set, or layers/masks don't overlap.
Areamust be on for the Area to detect;monitoringlets others detect it.monitorable - RayCast2D/3D read stale or no data if is false, or if you read it before physics updated — read in
enabled, and call_physics_processafter moving it within the same tick.force_raycast_update() - Forgetting a (or leaving it empty) means the body never collides.
CollisionShape - Fast objects tunnel through thin walls; enable continuous CD on the RigidBody
() or use a raycast-based check.
continuous_cd - excludes its own body? Pass
intersect_ray(anquery.exclude = [self.get_rid()], not an array of nodes) to skip self-hits.Array[RID]
- 混淆碰撞层与掩码是最常见的错误。碰撞层 = "我是什么";掩码 = "我要检测什么"。若A要检测B,B的碰撞层必须在A的掩码中。检测可以是单向的。
- 通过移动RigidBody会干扰物理求解器,导致穿模/抖动。应使用冲量/力、设置
position,或linear_velocity该物体。若需瞬移,应在freeze内设置位置并重置速度。_integrate_forces - Area未触发信号:当monitoring和monitorable均未开启,或碰撞层/掩码不重叠时,Area不会触发信号。必须开启才能让Area检测其他对象;
monitoring开启才能让其他对象检测该Area。monitorable - RayCast2D/3D读取到过期或无数据:若为false,或在物理更新前读取数据,会出现此问题——应在
enabled中读取,且在同一帧移动射线后调用_physics_process。force_raycast_update() - 遗漏(或留空)会导致物理体无法发生碰撞。
CollisionShape - 快速移动的对象穿模:开启RigidBody的连续碰撞检测(),或使用基于射线投射的检测。
continuous_cd - 排除自身? 传入
intersect_ray(query.exclude = [self.get_rid()]类型,而非节点数组)即可跳过自身碰撞。Array[RID]
References
参考资料
- For , joints, one-way collision,
_integrate_forcesdirect access, shape queries (PhysicsServer), and 3Dintersect_shape, readmove_and_collide.references/bodies-and-queries.md
- 关于、关节、单向碰撞、直接访问
_integrate_forces、形状查询(PhysicsServer)以及3D的intersect_shape,请阅读move_and_collide。references/bodies-and-queries.md
Related skills
相关技能
- — kinematic
godot-2d-movementcontrollers.CharacterBody2D - — tile collision shapes and their layers.
godot-tilemap - — engine-agnostic feel: timestep, mass, drag, CCD.
physics-tuning - — 3D scene setup these bodies live in.
godot-3d-essentials
- — 运动学
godot-2d-movement控制器。CharacterBody2D - — 瓦片碰撞形状及其层设置。
godot-tilemap - — 引擎无关的物理手感调优:时间步长、质量、阻力、连续碰撞检测。
physics-tuning - — 这些物理体所在的3D场景设置。
godot-3d-essentials