bevy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bevy Game Development Skill

Bevy游戏开发技能

A specialized skill for developing games and applications using the Bevy game engine, based on real-world experience building complex Bevy projects.
本技能基于开发复杂Bevy项目的实战经验,专为使用Bevy游戏引擎开发游戏及应用程序打造。

When to Use This Skill

何时使用本技能

Invoke this skill when:
  • Implementing features in a Bevy game or application
  • Designing component architectures for ECS
  • Creating or debugging Bevy systems
  • Working with Bevy's UI system
  • Building and testing Bevy projects
  • Troubleshooting common Bevy issues
  • Organizing project structure for Bevy applications
在以下场景中调用本技能:
  • 在Bevy游戏或应用中实现功能
  • 为ECS设计组件架构
  • 创建或调试Bevy系统
  • 使用Bevy的UI系统
  • 构建和测试Bevy项目
  • 排查Bevy常见问题
  • 为Bevy应用规划项目结构

Before You Start: Essential Bevy Tips

开始前:Bevy必备提示

⚠️ Bevy 0.17 Breaking Changes

⚠️ Bevy 0.17 破坏性变更

If working with Bevy 0.17, be aware of significant API changes:
  • Material handles now wrapped in
    MeshMaterial3d<T>
    (not
    Handle<T>
    )
  • Event system replaced with observer pattern (
    commands.trigger()
    ,
    add_observer()
    )
  • Color arithmetic operations removed (use component extraction)
See
references/bevy_specific_tips.md
for complete Bevy 0.17 migration guide and examples.
若使用Bevy 0.17,请注意重大API变更:
  • 材质句柄现在被
    MeshMaterial3d<T>
    包裹(而非
    Handle<T>
  • 事件系统替换为观察者模式(
    commands.trigger()
    add_observer()
  • 移除了颜色算术运算(改用组件提取)
完整的Bevy 0.17迁移指南及示例请查阅
references/bevy_specific_tips.md

Consult Bevy Registry Examples First

先查阅Bevy Registry示例

The registry examples are your bible. Always check them before implementing new features.
Location:
bash
~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/bevy-0.17.1/examples
There are MANY examples covering all aspects of Bevy development. Review relevant examples to understand best practices and working patterns.
Registry示例是你的“圣经”。在实现新功能前务必先查阅这些示例。
位置:
bash
~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/bevy-0.17.1/examples
这里有大量覆盖Bevy开发各方面的示例。查看相关示例以了解最佳实践和工作模式。

Use Plugin Structure

使用插件结构

Break your app into discrete modules using plugins. This improves organization and makes code discoverable.
rust
pub struct CombatPlugin;

impl Plugin for CombatPlugin {
    fn build(&self, app: &mut App) {
        app
            .add_event::<DamageEvent>()
            .add_systems(Update, (process_damage, check_death));
    }
}
See
references/bevy_specific_tips.md
for detailed plugin patterns and examples.
将应用拆分为独立的模块插件,这能提升代码的组织性和可发现性。
rust
pub struct CombatPlugin;

impl Plugin for CombatPlugin {
    fn build(&self, app: &mut App) {
        app
            .add_event::<DamageEvent>()
            .add_systems(Update, (process_damage, check_death));
    }
}
详细的插件模式及示例请查阅
references/bevy_specific_tips.md

Design Before Coding

编码前先设计

Pure ECS demands careful data modeling. It's hard to search a massive list of systems in one file!
Before implementing:
  1. Design the data model (entities, components, events, systems)
  2. Check Bevy examples for similar patterns
  3. Review docs and existing code
  4. Create a plugin for the feature domain
See
references/bevy_specific_tips.md
for domain-driven design guidance.
纯ECS需要严谨的数据建模。在单个文件中搜索大量系统是非常困难的!
实现前请:
  1. 设计数据模型(实体、组件、事件、系统)
  2. 查阅Bevy示例中的类似模式
  3. 阅读文档和现有代码
  4. 为功能领域创建插件
领域驱动设计指南请查阅
references/bevy_specific_tips.md

Core Development Principles

核心开发原则

Think in ECS Terms

用ECS思维思考

Bevy is an Entity Component System (ECS) engine. Always think in terms of data (components) and transformations (systems), not objects and methods.
Separation of Concerns:
  • Components = Pure data, no logic
  • Systems = Pure logic, operate on components
  • Events = Communication between systems
  • Resources = Global state (use sparingly)
Bevy是一款实体组件系统(ECS)引擎。始终从**数据(组件)转换(系统)**的角度思考,而非对象和方法。
关注点分离:
  • 组件 = 纯数据,无逻辑
  • 系统 = 纯逻辑,操作组件
  • 事件 = 系统间的通信方式
  • 资源 = 全局状态(谨慎使用)

Component-Driven Design

组件驱动设计

Keep components focused:
rust
// ✅ GOOD: Small, focused components
#[derive(Component)]
pub struct Health { pub current: f32, pub max: f32 }

#[derive(Component)]
pub struct Armor { pub defense: f32 }

// ❌ BAD: Monolithic component
#[derive(Component)]
pub struct CombatStats {
    pub health: f32,
    pub armor: f32,
    pub strength: f32,
    // ... wastes memory for entities that only have some stats
}
Add helper methods via impl blocks:
rust
impl Health {
    pub fn is_alive(&self) -> bool {
        self.current > 0.0
    }

    pub fn percentage(&self) -> f32 {
        self.current / self.max
    }
}
For detailed component patterns, see
references/ecs_patterns.md
.
保持组件聚焦:
rust
// ✅ 推荐:小巧、聚焦的组件
#[derive(Component)]
pub struct Health { pub current: f32, pub max: f32 }

#[derive(Component)]
pub struct Armor { pub defense: f32 }

// ❌ 不推荐:单体式组件
#[derive(Component)]
pub struct CombatStats {
    pub health: f32,
    pub armor: f32,
    pub strength: f32,
    // ... 对只拥有部分属性的实体来说是内存浪费
}
通过impl块添加辅助方法:
rust
impl Health {
    pub fn is_alive(&self) -> bool {
        self.current > 0.0
    }

    pub fn percentage(&self) -> f32 {
        self.current / self.max
    }
}
详细的组件模式请查阅
references/ecs_patterns.md

System Design and Ordering

系统设计与排序

Order systems by dependencies:
rust
.add_systems(
    Update,
    (
        // 1. Input processing
        handle_input,

        // 2. State changes
        process_events,
        update_state,

        // 3. Derive properties from state
        calculate_derived_values,

        // 4. Visual updates
        update_materials,
        update_animations,

        // 5. UI updates (must run last)
        update_ui_displays,
    ),
)
Use change detection to optimize:
rust
// Only process entities where Health changed
pub fn update_health_bar(
    query: Query<(&Health, &mut HealthBar), Changed<Health>>,
) {
    for (health, mut bar) in query.iter_mut() {
        bar.width = health.percentage() * 100.0;
    }
}
For detailed query patterns and system design, see
references/ecs_patterns.md
.
按依赖关系排序系统:
rust
.add_systems(
    Update,
    (
        // 1. 输入处理
        handle_input,

        // 2. 状态变更
        process_events,
        update_state,

        // 3. 从状态派生属性
        calculate_derived_values,

        // 4. 视觉更新
        update_materials,
        update_animations,

        // 5. UI更新(必须最后运行)
        update_ui_displays,
    ),
)
使用变更检测优化性能:
rust
// 仅处理Health组件发生变化的实体
pub fn update_health_bar(
    query: Query<(&Health, &mut HealthBar), Changed<Health>>,
) {
    for (health, mut bar) in query.iter_mut() {
        bar.width = health.percentage() * 100.0;
    }
}
详细的查询模式和系统设计请查阅
references/ecs_patterns.md

Build and Testing Workflow

构建与测试工作流

Build Commands

构建命令

Development (faster iteration):
bash
cargo build --features bevy/dynamic_linking
  • Uses dynamic linking for faster compile times
  • 2-3x faster than release builds
  • Only use during development
  • CRITICAL: Always use this for development builds
Quick Check:
bash
cargo check
  • Fastest way to verify compilation
  • Use after every significant change
Release (production):
bash
cargo build --release
  • Full optimization
  • Use for final testing and distribution
开发环境(迭代更快):
bash
cargo build --features bevy/dynamic_linking
  • 使用动态链接以加快编译速度
  • 比发布版构建快2-3倍
  • 仅在开发期间使用
  • **重要提示:**开发构建务必使用此命令
快速检查:
bash
cargo check
  • 验证编译的最快方式
  • 每次重大修改后使用
发布版(生产环境):
bash
cargo build --release
  • 完全优化
  • 用于最终测试和分发

Build Management - CRITICAL

构建管理 - 重要提示

DO NOT delete target binaries freely! Bevy takes minutes to rebuild from scratch.
  • Avoid
    cargo clean
    unless absolutely necessary
  • Each clean rebuild costs valuable development time
  • Be mindful of versions, targets, and crate dependencies getting tangled
  • Bevy is under active development - stick to one version per project
See
references/bevy_specific_tips.md
for detailed build optimization and version management.
**请勿随意删除target目录下的二进制文件!**Bevy从头重建需要数分钟时间。
  • 除非绝对必要,否则避免使用
    cargo clean
  • 每次清理重建都会耗费宝贵的开发时间
  • 注意版本、目标平台和 crate 依赖的混乱问题
  • Bevy正处于活跃开发中 - 每个项目坚持使用一个版本
详细的构建优化和版本管理请查阅
references/bevy_specific_tips.md

Testing Workflow

测试工作流

  1. After component changes: Run
    cargo check
  2. After system changes: Run
    cargo check
    then
    cargo build --features bevy/dynamic_linking
  3. Manual testing:
    • Does the game launch?
    • Do the new features work?
    • Are console logs showing expected output?
    • Do visual changes appear correctly?
Validation points - Let the user test at these milestones:
  • New entity spawned
  • New mechanic implemented
  • Visual effects added
  • Major system changes
  1. **组件修改后:**运行
    cargo check
  2. **系统修改后:**先运行
    cargo check
    ,再运行
    cargo build --features bevy/dynamic_linking
  3. 手动测试:
    • 游戏能否正常启动?
    • 新功能是否正常工作?
    • 控制台日志是否显示预期输出?
    • 视觉变更是否正确显示?
验证节点 - 让用户在以下里程碑进行测试:
  • 新实体已生成
  • 新机制已实现
  • 视觉效果已添加
  • 主要系统已变更

UI Development in Bevy

UI开发(Bevy)

Bevy uses a flexbox-like layout system. Follow the marker component pattern:
1. Create marker components:
rust
#[derive(Component)]
pub struct HealthBar;

#[derive(Component)]
pub struct ScoreDisplay;
2. Setup in Startup:
rust
pub fn setup_ui(mut commands: Commands) {
    commands.spawn((
        HealthBar,
        Node {
            position_type: PositionType::Absolute,
            left: Val::Px(10.0),
            top: Val::Px(10.0),
            width: Val::Px(200.0),
            height: Val::Px(20.0),
            ..default()
        },
        BackgroundColor(Color::srgba(0.8, 0.2, 0.2, 0.9)),
    ));
}
3. Update in Update:
rust
pub fn update_health_ui(
    health: Query<&Health, With<Player>>,
    mut ui: Query<&mut Node, With<HealthBar>>,
) {
    if let (Ok(health), Ok(mut node)) = (health.get_single(), ui.get_single_mut()) {
        node.width = Val::Px(health.percentage() * 200.0);
    }
}
For detailed UI patterns including positioning, styling, and text updates, see
references/ui_development.md
.
Bevy使用类flexbox的布局系统。遵循标记组件模式:
1. 创建标记组件:
rust
#[derive(Component)]
pub struct HealthBar;

#[derive(Component)]
pub struct ScoreDisplay;
2. 在Startup阶段设置:
rust
pub fn setup_ui(mut commands: Commands) {
    commands.spawn((
        HealthBar,
        Node {
            position_type: PositionType::Absolute,
            left: Val::Px(10.0),
            top: Val::Px(10.0),
            width: Val::Px(200.0),
            height: Val::Px(20.0),
            ..default()
        },
        BackgroundColor(Color::srgba(0.8, 0.2, 0.2, 0.9)),
    ));
}
3. 在Update阶段更新:
rust
pub fn update_health_ui(
    health: Query<&Health, With<Player>>,
    mut ui: Query<&mut Node, With<HealthBar>>,
) {
    if let (Ok(health), Ok(mut node)) = (health.get_single(), ui.get_single_mut()) {
        node.width = Val::Px(health.percentage() * 200.0);
    }
}
详细的UI模式(包括定位、样式和文本更新)请查阅
references/ui_development.md

Incremental Development Strategy

增量开发策略

Phase-Based Development

分阶段开发

Break features into phases:
Phase 1: Foundation - Core components and basic systems Phase 2: Content - Add entities and populate world Phase 3: Polish - UI improvements and visual effects Phase 4: Advanced Features - Complex mechanics and AI
将功能拆分为多个阶段:
阶段1:基础 - 核心组件和基础系统 阶段2:内容 - 添加实体并填充世界 阶段3:打磨 - UI改进和视觉效果 阶段4:高级功能 - 复杂机制和AI

Iteration Pattern

迭代模式

1. Plan → 2. Implement → 3. Build → 4. Test → 5. Refine
     ↑                                           ↓
     ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←
Each phase should have:
  1. Clear success criteria (checklist of what works)
  2. Manual test cases (step-by-step testing procedures)
  3. User validation points (when to let user test)
1. 规划 → 2. 实现 → 3. 构建 → 4. 测试 → 5. 优化
     ↑                                           ↓
     ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←
每个阶段应包含:
  1. 明确的成功标准(功能正常的检查清单)
  2. 手动测试用例(分步测试流程)
  3. 用户验证节点(让用户测试的时机)

Performance Optimization

性能优化

When to Optimize

何时优化

For prototypes (7-100 entities):
  • No optimization needed
  • Change detection is sufficient
  • Focus on features, not performance
For production (100+ entities):
  • Use spatial partitioning for proximity queries
  • Batch material updates
  • Consider Fixed timestep for physics
  • Profile before optimizing
原型阶段(7-100个实体):
  • 无需优化
  • 变更检测已足够
  • 专注于功能,而非性能
生产阶段(100+个实体):
  • 对邻近查询使用空间分区
  • 批量更新材质
  • 考虑为物理系统使用固定时间步长
  • 先分析再优化

Query Optimization Tips

查询优化技巧

  1. Use change detection:
    Query<&Component, Changed<Component>>
  2. Filter early:
    Query<&A, (With<B>, Without<C>)>
    instead of filtering in loops
  3. Check resource changes: Return early if resource hasn't changed
  1. 使用变更检测:
    Query<&Component, Changed<Component>>
  2. **尽早过滤:**使用
    Query<&A, (With<B>, Without<C>)>
    而非在循环中过滤
  3. **检查资源变更:**若资源未变更则提前返回

Common Pitfalls to Avoid

需避免的常见陷阱

Critical mistakes and their solutions are documented in
references/common_pitfalls.md
. Key pitfalls include:
  1. Forgetting to register systems in
    main.rs
  2. Borrowing conflicts (use
    get_many_mut
    for multiple mutations)
  3. Not using
    Changed<T>
    for expensive operations
  4. Wrong system ordering (input → state → derived → visual → UI)
  5. Entity queries after despawn (use
    if let Ok()
    pattern)
  6. Material/asset handle confusion (store handles properly)
Review
references/common_pitfalls.md
before implementing complex features.
关键错误及其解决方案记录在
references/common_pitfalls.md
中。主要陷阱包括:
  1. 忘记在
    main.rs
    中注册系统
  2. 借用冲突(使用
    get_many_mut
    进行多个突变操作)
  3. 对昂贵操作未使用
    Changed<T>
  4. 系统排序错误(输入→状态→派生→视觉→UI)
  5. 实体销毁后进行查询(使用
    if let Ok()
    模式)
  6. 材质/资源句柄混淆(正确存储句柄)
在实现复杂功能前,请查阅
references/common_pitfalls.md

Using Subagents for Complex Features

使用子代理实现复杂功能

When implementing multi-step features, use the plan-implementer subagent with this structure:
Goal: [One sentence describing end state]

Current State: [What exists now]

Requirements: [Numbered list of what to build]

Implementation Steps: [Suggested approach]

Success Criteria: [How to verify it works]

Notes: [Important context, edge cases, design principles]
Example:
Implement Health System

Goal: Implement a health system with damage, healing, and death mechanics.

Current State:
- Player entity exists
- No health tracking yet

Requirements:
1. Create Health component with current/max values
2. Create DamageEvent for dealing damage
3. Create system to process damage events
4. Add death detection when health reaches 0
5. Add visual health bar UI

Implementation Steps:
1. Create Health component in src/components/properties.rs
2. Create DamageEvent in src/events.rs
3. Create process_damage system in src/systems/combat.rs
4. Create check_death system
5. Create health bar UI in src/systems/ui/health_bar.rs
6. Register all systems in main.rs in correct order

Success Criteria:
- Player spawns with Health component
- Damage events reduce health
- Health bar updates when health changes
- Entity despawns when health reaches 0
- Code compiles without errors
在实现多步骤功能时,使用计划实现子代理并遵循以下结构:
目标:[描述最终状态的一句话]

当前状态:[现有内容]

需求:[待构建内容的编号列表]

实现步骤:[建议的方法]

成功标准:[验证功能正常的方式]

注意事项:[重要上下文、边缘情况、设计原则]
示例:
实现生命值系统

目标:实现包含伤害、治疗和死亡机制的生命值系统。

当前状态:
- 玩家实体已存在
- 尚未实现生命值追踪

需求:
1. 创建包含当前值/最大值的Health组件
2. 创建用于造成伤害的DamageEvent
3. 创建处理伤害事件的系统
4. 添加生命值归0时的死亡检测
5. 添加视觉化生命值条UI

实现步骤:
1. 在src/components/properties.rs中创建Health组件
2. 在src/events.rs中创建DamageEvent
3. 在src/systems/combat.rs中创建process_damage系统
4. 创建check_death系统
5. 在src/systems/ui/health_bar.rs中创建生命值条UI
6. 在main.rs中按正确顺序注册所有系统

成功标准:
- 玩家生成时带有Health组件
- 伤害事件会减少生命值
- 生命值变化时生命值条会更新
- 生命值归0时实体被销毁
- 代码编译无错误

Project Structure Reference

项目结构参考

For details on recommended file organization, module structure, and component file patterns, see
references/project_structure.md
.
推荐的文件组织、模块结构和组件文件模式详情请查阅
references/project_structure.md

References

参考资料

This skill includes detailed reference documentation:
  • references/bevy_specific_tips.md
    - START HERE: Registry examples, plugin structure, build optimization, version management, domain-driven design for ECS
  • references/ecs_patterns.md
    - Component design patterns, query patterns, and common ECS design patterns (Derivation, State Machine, Threshold/Trigger, Event-Driven, Initialization)
  • references/ui_development.md
    - Bevy UI hierarchy, component patterns, layout tips, positioning, styling, and text updates
  • references/common_pitfalls.md
    - Common mistakes and their solutions (system registration, borrowing conflicts, change detection, system ordering, entity queries, asset handles)
  • references/project_structure.md
    - Recommended file organization, module structure, component file patterns, and change detection
Load these references as needed to inform implementation decisions.
本技能包含详细的参考文档:
  • references/bevy_specific_tips.md
    - **入门首选:**Registry示例、插件结构、构建优化、版本管理、ECS领域驱动设计
  • references/ecs_patterns.md
    - 组件设计模式、查询模式及常见ECS设计模式(派生、状态机、阈值/触发器、事件驱动、初始化)
  • references/ui_development.md
    - Bevy UI层级、组件模式、布局技巧、定位、样式和文本更新
  • references/common_pitfalls.md
    - 常见错误及其解决方案(系统注册、借用冲突、变更检测、系统排序、实体查询、资源句柄)
  • references/project_structure.md
    - 推荐的文件组织、模块结构、组件文件模式和变更检测
根据需要加载这些参考资料,为实现决策提供依据。

Additional Resources

额外资源

Bevy Documentation:
ECS Design Principles:
  • Prefer composition over inheritance
  • One component = one concern
  • Systems should be pure functions
  • Use events to decouple systems
  • Design data model before coding
  • Check registry examples first

Remember: Think in terms of data (components) and transformations (systems), not objects and methods. Always consult registry examples and design your data model before diving into implementation. This is the key to effective Bevy development.
Bevy官方文档:
ECS设计原则:
  • 优先组合而非继承
  • 一个组件对应一个关注点
  • 系统应为纯函数
  • 使用事件解耦系统
  • 编码前先设计数据模型
  • 先查阅Registry示例

**记住:**从数据(组件)和转换(系统)的角度思考,而非对象和方法。始终查阅Registry示例,在开始实现前设计好数据模型。这是高效Bevy开发的关键。