К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

godot-physics — скилл для Claude Code: что делает и как установить

Настраивает физические тела Godot 4.7, слои коллизий, триггеры Area и лучи в 2D и 3D. Помогает избежать ошибок с перекрытием масок и дёрганием RigidBody.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill godot-physics -a claude-code
Открыть на GitHub

Что делает godot-physics

Скилл даёт правила работы с физикой Godot 4.7 в 2D и 3D. Он помогает выбрать подходящий узел под задачу: неподвижный StaticBody, полностью симулируемый RigidBody или триггерную зону Area. В инструкциях зафиксированы принципы разграничения collision layers и masks, чтобы объекты не проходили сквозь стены и реагировали только на нужные группы.

Для детекции коллизий описаны подходы со связкой сигналов body_entered у Area, использование нод RayCast2D и RayCast3D, а также разовые запросы через PhysicsRayQueryParameters2D и intersect_ray. Скилл прямо запрещает двигать RigidBody через свойство position во избежание туннелирования. Управлять им нужно импульсами, силами или сменой linear_velocity.

При переходе на Godot 4.6 и новее важно помнить: в 3D движок Jolt Physics включён по умолчанию. Из-за этого параметр face_index в рейкастах возвращает -1, пока его явно не включат в настройках проекта ценой 25% памяти на коллизии сеток. Скилл не охватывает кинематическое движение персонажей с move_and_slide и настройку тайлмапов — для них нужны отдельные правила.

Какие задачи решает

  • разграничить collision layers и collision masks между игроком, врагами и препятствиями
  • настроить зоны урона и триггеры через сигналы Area2D или Area3D
  • применить импульсы и силы к RigidBody3D без прямого изменения координат
  • реализовать разовую проверку препятствий через intersect_ray с исключением собственного тела

Примеры запросов агенту

  • Настрой слои коллизий в GDScript: игрок на первом слое, сканирует стены на втором и врагов на третьем
  • Сделай триггер получения урона на базе Area2D с сигналом body_entered
  • Напиши функцию проверки земли под объектом через PhysicsRayQueryParameters2D

Как установить godot-physics

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill godot-physics -a claude-code

2Вручную: положить файлы

~/.claude/skills/godot-physics/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/godot-physics/

Из того же набора40

Весь набор →
game-feel gamedev-skills Скилл учит агента добавлять отклик к игровым действиям: тряску камеры, стоп-кадр, твины с easing, сквош и отброс. Для случаев, когда механика работает, но ощущается ватной. Claude Code CX Codex Cursor +1 9 400установок game-ui-ux gamedev-skills Архитектурный скилл для создания адаптивных игровых интерфейсов, стека экранов и навигации с геймпада без покадрового опроса состояния. Claude Code CX Codex Cursor +1 9 200установок level-design gamedev-skills Помогает спроектировать игровой уровень от блокута до плейтеста: маршруты, темп, препятствия и столкновения. Нужен при работе с whitebox, критическим путём и геймплейными комнатами. Claude Code CX Codex Cursor +1 7 500установок camera-systems gamedev-skills Рецепты для игровых камер в 2D и 3D: плавное следование, мёртвые зоны, опережение движения и обработка столкновений для Godot и Unity. Claude Code CX Codex Cursor +1 7 100установок audio-design gamedev-skills Скилл учит раскладывать игровой звук по шинам, глушить музыку под голос и собирать адаптивный саундтрек слоями. Примеры кода — на GDScript под Godot 4.7, с пометками для Unity. Claude Code CX Codex Cursor +1 7 100установок performance-optimization gamedev-skills Скилл учит искать узкое место в игре по профайлеру движка, а не по догадке, и даёт набор правок: пулы объектов, батчинг, отказ от лишних аллокаций. Claude Code CX Codex Cursor +1 7 100установок game-ai gamedev-skills Помогает проектировать логику врагов и NPC: конечные автоматы, деревья поведения, алгоритмы руления и поиск пути A*. Пригодится при сборке поведения ботов для любого движка. Claude Code CX Codex Cursor +1 7 100установок input-systems gamedev-skills Архитектура игровых управлений: отображение клавиш на действия, перекоординирование с проверкой конфликтов, поддержка клавиатуры, геймпада и сенсора, мёртвые зоны, буферизация и coyote time. Claude Code CX Codex Cursor +1 6 800установок

Похожие

mod-any-game rehan-remade Скилл для создания модов к ПК-играм: от разведки движка и резервных копий сейвов до генерации ассетов и сборки первого рабочего прототипа. Claude Code CX Codex Cursor +1 1 500установок orbit-card heygen-com Скилл для встраивания готового 10-секундного 3D-блока HyperFrames: карточка фичи облетает сферу из точек по траектории камеры из Blender. Claude Code CX Codex Cursor +1 9 800установок sdf earthtojake Скилл создаёт и проверяет SDFormat-файлы для моделей и миров, а затем помогает подготовить их к передаче в симулятор. Claude Code CX Codex Cursor +1 10 500установок urdf earthtojake Скилл помогает создавать, проверять и отлаживать описания роботов в формате URDF. Пригодится для работы со звеньями, сочленениями и геометрией. Claude Code CX Codex Cursor +1 10 400установок hatch-pet официальный openai Создаёт и упаковывает анимированных питомцев и спрайт-листы для Codex. Пригодится, когда нужен персонаж по описанию, изображению или фирменным ориентирам. Claude Code CX Codex Cursor +1 3 300установок gcode earthtojake Нарезает модели STL, 3MF и OBJ в G-code через OrcaSlicer. Подходит, когда нужно подготовить файл для печати без подключения к принтеру. Claude Code CX Codex Cursor +1 9 500установок dxf earthtojake Скилл собирает и проверяет 2D DXF-чертежи из Python-скриптов на build123d: контуры, прокладки, панели, развёртки под лазер. Claude Code CX Codex Cursor +1 9 100установок

Вопросы о godot-physics

Как установить godot-physics в Claude Code?

Выполните команду npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill godot-physics -a claude-code. Файл навыка сохранится по пути ~/.claude/skills/godot-physics/SKILL.md.

Чем collision layers отличаются от collision masks в этом скилле?

Слой (layer) определяет, где физически находится объект. Маска (mask) задаёт список слоёв, с которыми этот объект взаимодействует и за которыми следит.

Почему в 3D-проектах на Godot 4.7 луч не возвращает face_index?

В проектах Godot 4.6+ стандартным 3D-движком стал Jolt Physics, где face_index всегда равен -1. Его нужно активировать вручную в Project Settings ценой 25% расхода памяти для ConcavePolygonShape3D.

Исходный текст

SKILL.md · Apache-2.0
---
name: godot-physics
description: >
  Use Godot 4.7 physics bodies and detection in 2D and 3D: RigidBody, StaticBody,
  Area, and CharacterBody; collision layers vs masks; contact/overlap signals; and
  raycasts (RayCast nodes and direct space-state queries). Use when configuring
  collision layers/masks, detecting overlaps with Area2D/Area3D, applying forces to a
  RigidBody, or casting rays in a Godot project (.tscn with physics bodies), including
  3D projects running Jolt Physics, the default 3D engine for projects created in 4.6+.
---

# Godot Physics (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 `2D`/`3D` suffix). Targets
**Godot 4.7**. In 3D, projects created with Godot 4.6 or later run **Jolt Physics** by
default; older projects keep **GodotPhysics3D** unless someone switched them. 2D always
uses Godot's own 2D engine.

## When to use

- Use when choosing between body types, setting collision layers/masks so the right
  things collide, detecting overlaps (triggers, hurtboxes) with `Area`, applying
  forces/impulses to a `RigidBody`, or casting rays for line-of-sight/ground checks.

**When *not* to use:** kinematic character controllers (`move_and_slide`) →
`godot-2d-movement`; tile collision setup → `godot-tilemap`; tuning the *feel* of physics
(timestep, mass, jitter) → `physics-tuning`.

## Core workflow

1. **For 3D, check which engine runs** before debugging behavior: Project Settings >
   Physics > 3D > Physics Engine (`[physics]` `3d/physics_engine="Jolt Physics"` in
   `project.godot`). Projects created in 4.6+ get Jolt written there by default; with no
   such line (`DEFAULT`) the engine is GodotPhysics3D. The API is the same, but joints,
   ray-cast face indices, kinematic contacts, and collision margins behave differently
   (see Pitfalls).
2. **Choose the body type:**
   - `StaticBody` — never moves (floors, walls). Collides, no simulation.
   - `RigidBody` — fully simulated (gravity, forces, bouncing). Don't set its
     `position` directly; apply forces/impulses or set `linear_velocity`.
   - `CharacterBody` — script-driven kinematic (see `godot-2d-movement`).
   - `Area` — detects overlaps and can apply gravity/damping; no solid collision.
   Every body needs a `CollisionShape` (or `CollisionPolygon`) child.
3. **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.
4. **Detect overlaps** with `Area` signals (`body_entered`, `area_entered`).
5. **Drive RigidBodies with forces/impulses**, or override `_integrate_forces` for full
   control.
6. **Cast rays** with a `RayCast2D/3D` node (polled each frame) or a one-shot space-state
   query from code.

## Patterns

### 1. Collision layers vs masks (set from code)

```gdscript
# Player is on layer 1, scans layers 2 (walls) and 3 (enemies).
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
```

### 2. Area2D as a trigger / hurtbox

```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)
```

### 3. Applying force and impulse to a 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.
```

### 4. Raycast two ways

```gdscript
# A) RayCast2D node: enable it, then poll after physics has updated.
@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()

# B) One-shot query from code (no node needed).
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
```

## Pitfalls

- **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 `position`** fights the solver and causes tunneling/jitter.
  Use impulses/forces, set `linear_velocity`, or `freeze` it. To teleport, set position
  and zero the velocities inside `_integrate_forces`.
- **`Area` doesn't fire** when neither monitoring nor monitorable is set, or layers/masks
  don't overlap. `monitoring` must be on for the Area to detect; `monitorable` lets others
  detect it.
- **RayCast2D/3D read stale or no data** if `enabled` is false, or if you read it before
  physics updated — read in `_physics_process`, and call `force_raycast_update()` after
  moving it within the same tick.
- **Forgetting a `CollisionShape`** (or leaving it empty) means the body never collides.
- **Fast objects tunnel** through thin walls; enable **continuous CD** on the RigidBody
  (`continuous_cd`) or use a raycast-based check.
- **`intersect_ray` excludes its own body?** Pass `query.exclude = [self.get_rid()]` (an
  `Array[RID]`, not an array of nodes) to skip self-hits.

### Jolt Physics (3D) differences

- **`face_index` is always `-1`** in `intersect_ray()` / `RayCast3D` results under Jolt.
  Turn on Project Settings > Physics > Jolt Physics 3D > Queries > Enable Ray Cast Face
  Index if you need it (it costs roughly 25% more memory for `ConcavePolygonShape3D`).
- **A joint with only one body gets inverted limits after switching engines.** Jolt treats
  the lone body as `node_b` with `node_a` as the world; GodotPhysics3D always treats it as
  `node_a`. Assign the body to the slot Jolt expects, or use Physics > Jolt Physics 3D >
  Joints > World Node for compatibility with an older project.
- **Joint soft-limit properties do nothing** under Jolt: `bias`/`damping`/`impulse_clamp` on
  `PinJoint3D`; `bias`/`softness`/`relaxation` on `HingeJoint3D` and `ConeTwistJoint3D`;
  `angular_*` and limit softness/restitution/damping on `SliderJoint3D`; limit
  softness/restitution/damping/erp on `Generic6DOFJoint3D`. Godot warns when they are set
  to non-default values.
- **A frozen kinematic `RigidBody3D` reports no contacts** with static or kinematic bodies,
  even with `max_contacts_reported > 0`. Enable Physics > Jolt Physics 3D > Simulation >
  Generate All Kinematic Contacts if gameplay depends on those contacts.
- **Shape `margin` shrinks the shape instead of padding it** under Jolt, so sizes stay
  true but shape queries can return odd normals on small shapes; the effective margin comes
  from Physics > Jolt Physics 3D > Collisions > Collision Margin Fraction.
- **`Area3D` now fires `body_entered` for `SoftBody3D`** under Jolt (GodotPhysics3D never
  did). Filter soft bodies out with layers/masks if the old behavior is expected.
- **A `WorldBoundaryShape3D` floor sits at the wrong height after upgrading to 4.7** → under
  Jolt, 4.7 reads `plane.d` with Godot's sign convention, the opposite of 4.6; flip the sign
  of `d` in projects tuned on 4.6. Jolt also caps the plane's effective size (Physics > Jolt
  Physics 3D > Limits > World Boundary Shape Size), so bodies far from the origin can fall
  off an "infinite" floor.

## References

- For `_integrate_forces`, joints, one-way collision, `PhysicsServer` direct access,
  shape queries (`intersect_shape`), and 3D `move_and_collide`, read
  `references/bodies-and-queries.md`.
- Jolt specifics: Godot docs "Using Jolt Physics"
  (`https://docs.godotengine.org/en/stable/tutorials/physics/using_jolt_physics.html`).

## Related skills

- `godot-2d-movement` — kinematic `CharacterBody2D` controllers.
- `godot-tilemap` — tile collision shapes and their layers.
- `physics-tuning` — engine-agnostic feel: timestep, mass, drag, CCD.
- `godot-3d-essentials` — 3D scene setup these bodies live in.

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой