Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

bevy-physics-2d

БесплатноБез исполняемых скриптовНе проверен

Bevy ECS skill for 2D physics. Keywords: Bevy, physics, 2D, ECS, collision.

thedivergentaiот thedivergentai★ 1 019 звёзд на GitHub

Об этом скилле

Bevy 2D physics

When to use

Load this when a Bevy app needs simulated 2D bodies, triggers, or layer filtering before choosing a solver. Pair with bevy-character-movement for player motion that should not be a rigid body. Pair with bevy-spatial-queries for casts that also wait on a solver.

ECS shape

  • Components own velocity, mass, a circle radius, and a layer mask for props you simulate yourself.
  • Resources own gravity.
  • Systems integrate on FixedUpdate, then separate overlapping circles. .chain() runs separation after the step.
  • Schedule: the fixed step is the clock. A solver plugin can replace the integrator when you need joints and a spatial index. This file does not name that plugin's types. Player locomotion stays on bevy-character-movement.

Coming from Godot

Godot idea Bevy idiom
Simulated 2D prop Body2d plus Transform, integrated on FixedUpdate
Player locomotion bevy-character-movement, not this integrator
Trigger volumes An Aabb overlap that records occupants
Layers and masks A LayerMask you define, filtered in the overlap system

Scope

Gravity, velocity, circle overlap, and AABB triggers are ordinary components stepped on FixedUpdate. Joints, continuous collision, and a spatial index belong to a physics solver you add as a plugin. Casts that need that solver's world belong on bevy-spatial-queries.

Examples

[dependencies]
bevy = "0.20"

Integrate velocity under gravity, then push overlapping circles apart when their layer masks intersect. Both systems write Body2d and Transform, so they run as one chain.

#[derive(Component)]
struct Body2d {
    velocity: Vec2,
    mass: f32,
    radius: f32,
}

#[derive(Component)]
struct LayerMask {
    layer: u32,
    mask: u32,
}

#[derive(Resource)]
struct Gravity2d(Vec2);

fn integrate_2d(
    time: Res<Time<Fixed>>,
    gravity: Res<Gravity2d>,
    mut bodies: Query<(&mut Transform, &mut Body2d)>,
) {
    let dt = time.delta_secs();
    for (mut tf, mut body) in &mut bodies {
        body.velocity += gravity.0 * dt;
        tf.translation.x += body.velocity.x * dt;
        tf.translation.y += body.velocity.y * dt;
        if tf.translation.y < body.radius {
            tf.translation.y = body.radius;
            body.velocity.y = body.velocity.y.max(0.0);
        }
    }
}

fn masks_overlap(a: &LayerMask, b: &LayerMask) -> bool {
    (a.mask & b.layer) != 0 && (b.mask & a.layer) != 0
}

fn separate_circles(mut bodies: Query<(Entity, &mut Transform, &mut Body2d, &LayerMask)>) {
    let mut pairs: Vec<(Entity, Entity)> = Vec::new();
    for (a, tf_a, body_a, layer_a) in &bodies {
        for (b, tf_b, body_b, layer_b) in &bodies {
            if a.index() >= b.index() || !masks_overlap(layer_a, layer_b) {
                continue;
            }
            let delta = tf_b.translation.truncate() - tf_a.translation.truncate();
            let min = body_a.radius + body_b.radius;
            if delta.length() < min {
                pairs.push((a, b));
            }
        }
    }
    for (a, b) in pairs {
        let Ok([(_, mut tf_a, mut body_a, _), (_, mut tf_b, mut body_b, _)]) =
            bodies.get_many_mut([a, b])
        else {
            continue;
        };
        let delta = tf_b.translation.truncate() - tf_a.translation.truncate();
        let dist = delta.length();
        let min = body_a.radius + body_b.radius;
        if dist >= min || dist == 0.0 {
            continue;
        }
        let normal = delta / dist;
        let push = (min - dist) * 0.5;
        tf_a.translation.x -= normal.x * push;
        tf_a.translation.y -= normal.y * push;
        tf_b.translation.x += normal.x * push;
        tf_b.translation.y += normal.y * push;
        let rel = (body_b.velocity - body_a.velocity).dot(normal);
        if rel < 0.0 {
            let inv_a = 1.0 / body_a.mass.max(0.001);
            let inv_b = 1.0 / body_b.mass.max(0.001);
            let impulse = -rel / (inv_a + inv_b);
            body_a.velocity -= normal * impulse * inv_a;
            body_b.velocity += normal * impulse * inv_b;
        }
    }
}

pub struct Physics2dPlugin;

impl Plugin for Physics2dPlugin {
    fn build(&self, app: &mut App) {
        app.insert_resource(Gravity2d(Vec2::new(0.0, -9.8)))
            .add_systems(FixedUpdate, (integrate_2d, separate_circles).chain());
    }
}

An AABB trigger remembers who is inside. A ray against a circle reports the nearest hit along the segment.

#[derive(Component)]
struct AabbTrigger {
    half: Vec2,
}

#[derive(Component)]
struct Inside(Vec<Entity>);

#[derive(Component)]
struct Body2d {
    velocity: Vec2,
    mass: f32,
    radius: f32,
}

#[derive(Component)]
struct LayerMask {
    layer: u32,
    mask: u32,
}

fn fill_trigger(
    triggers: Query<(Entity, &Transform, &AabbTrigger)>,
    bodies: Query<(Entity, &Transform, &Body2d)>,
    mut occupants: Query<&mut Inside>,
) {
    f
Полный SKILL.md на GitHub

Установить bevy-physics-2d в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/ecs-ownership.md

FAQ

Что делает скилл bevy-physics-2d?

Bevy ECS skill for 2D physics. Keywords: Bevy, physics, 2D, ECS, collision.

Как установить скилл bevy-physics-2d?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл bevy-physics-2d запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить bevy-physics-2d с