PyBevy is in an early and experimental stage. The API is incomplete, subject to breaking changes without notice, and you should expect bugs. Many features are still under development.
Spawn a Thing!
Combining ECS with 2D and 3D rendering.
Introduction
In pybevy, everything is an entity with components. This includes cameras,
lights, 2D sprites, and 3D models.
This example shows how different kinds of objects are all just entities with different components. We will spawn:
- A 3D Camera
- A 2D Sprite
- A 3D Cube with a light source
They are all just entities, distinguished only by the components they have.
from pybevy.prelude import *The Setup System
We'll put all our spawning logic in a single Startup system.
Notice how we spawn different "things" using the same commands.spawn() function.
The only difference is the set of components we give each entity.
def setup(
commands: Commands,
meshes: ResMut[Assets[Mesh]],
materials: ResMut[Assets[StandardMaterial]],
asset_server: AssetServer,
):
# A 3D camera is an entity with `Camera3d` and a `Transform`.
commands.spawn(
Camera3d(),
Transform.from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3.ZERO, Vec3.Y),
)
# A 2D sprite is an entity with a `Sprite` and a `Transform`.
# We'll load its texture from a file.
commands.spawn(
Sprite(image=asset_server.load_image("branding/icon.png")),
Transform.from_xyz(-3.0, 2.0, 0.0),
)
# A 3D cube is an entity with a mesh, a material, and a transform.
commands.spawn(
Mesh3d(meshes.add(Cuboid.from_length(1.0))),
MeshMaterial3d(materials.add(Color.srgb_u8(124, 144, 255))),
Transform.from_xyz(0.0, 0.5, 0.0),
)
# A light is just an entity with a `PointLight` and a `Transform`.
commands.spawn(
PointLight(shadows_enabled=True),
Transform.from_xyz(4.0, 8.0, 4.0),
)
# We also need a ground plane for the 3D objects to sit on.
commands.spawn(
Mesh3d(meshes.add(Plane3d(Vec3.Y, Vec2(10.0, 10.0)))),
MeshMaterial3d(materials.add(Color.WHITE)),
)Running the App
We add DefaultPlugins and our setup system. When you run this, you'll
see the PyBevy logo sprite and the 3D cube rendered in the same window.
@entrypoint
def main(app: App) -> App:
return app.add_plugins(DefaultPlugins).add_systems(Startup, setup)
if __name__ == "__main__":
main().run()