2个版本
| 0.2.1 | 2021年12月26日 | 
|---|---|
| 0.2.0 | 2021年12月25日 | 
#15 in #prefab
74KB
 1K  SLoC
Bevy Lazy Prefabs
用于bevy中简单易读/易写的预制件文本文件的crate。
注意:这不是一个灵活的长期预制件解决方案,但它应该适用于简单的游戏和原型设计,以避免在代码中完全定义实体。
.Prefab文件
首先,编写一个.prefab文件并将其放在assets/prefabs目录中。
SomePrefab {                   // Prefab name is optional. Outer braces are required. 
    Transform {                // Components are listed by type name.
        translation : Vec3 {   // Component fields can be initialized inside nested curly braces.
            x: 15.0, y: 10.5,  // Any omitted fields will be initialized to default.
        },
    },
    Visible,                   // If you choose not to initialize any fields, the braces can be omitted entirely.
    Draw,
    SomeComponent {            // Custom components are supported
        some_int: 15,
    },
}
在上面的示例中,我们正在创建一个具有Transform、Visible、Draw和SomeComponent组件的预制件。在这种情况下,实体的变换将在实体生成时初始化为位置(15.0,10.0,0.0)。
自定义组件只有在派生自Reflect和Default,并且具有#[reflect)]属性时才会在预制件中起作用。大多数内置bevy类型已经满足这个约束。它们还必须在设置期间与[PrefabRegistry]注册。
上面的预制件并没有什么用处——实体将不会被渲染,因为它没有网格或材质。为此,我们可以使用build_commands::BuildPrefabCommand。
构建预制件命令
构建命令允许您包含需要额外步骤才能正确初始化的复杂组件,例如网格、材质或包。
可以编写自定义命令,但已包含了一些更常见的组件
- InsertSpriteBundle- 在实体上插入一个- SpriteBundle。可以指定- color和- texture_path。
- SetColorMaterial- 修改实体上的现有- ColorMaterial。
- LoadPrefab- 加载现有预制件并在当前实体上执行其构建步骤。
- InsertPbrBundle- 插入一个- PbrBundle。可以指定网格- shape、- size和- flip。
- InsertOrthographicCameraBundle- 插入一个- OrthographicCameraBundle。可以指定- scale。
- InsertPerspectiveCameraBundle- 插入一个- PerspectiveCameraBundle。可以指定- position和- looking_at。
示例
{
    InsertSpriteBundle! (          
        texture_path: "alien.png", 
        color: Color::RED,         
    ),
}
上面的 .prefab 文件将生成一个包含来自 SpriteBundle 所有组件的实体。精灵包的 ColorMaterial 组件将使用给定的纹理和颜色初始化。
注意这些 '字段' 并非直接指代包中的字段,而是可选属性,在构建命令中传递并用于初始化过程。这些属性如何使用由每个单独的构建命令定义。
生成预制体
一旦你的 .prefab 文件位于 assets/prefabs 目录中,你可以使用 [PrefabRegistry] 和 Commands 生成预制体。
use bevy::prelude::*;
use bevy_lazy_prefabs::*;
fn setup(mut commands: Commands, mut registry: ResMut<PrefabRegistry>) {
  let sprite = registry.load("sprite.prefab").unwrap();
  commands.spawn().insert_prefab(sprite);
  let cam = registry.load("cam_2d.prefab").unwrap();
  commands.spawn().insert_prefab(cam);
 }
依赖项
~32–75MB
~643K SLoC