Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/README.md
6585 views

Examples

These examples demonstrate the main features of Bevy and how to use them. To run an example, use the command cargo run --example <Example>, and add the option --features x11 or --features wayland to force the example to run on a specific window compositor, e.g.

cargo run --features wayland --example hello_world

⚠️ Note: for users of releases on crates.io!

There are often large differences and incompatible API changes between the latest crates.io release and the development version of Bevy in the git main branch!

If you are using a released version of bevy, you need to make sure you are viewing the correct version of the examples!

When you clone the repo locally to run the examples, use git checkout to get the correct version:

# `latest` always points to the newest release git checkout latest # or use a specific version git checkout v0.4.0

Table of Contents

The Bare Minimum

Hello, World!

ExampleDescription
hello_world.rsRuns a minimal example that outputs "hello world"

Cross-Platform Examples

2D Rendering

ExampleDescription
2D BloomIllustrates bloom post-processing in 2d
2D RotationDemonstrates rotating entities in 2D with quaternions
2D ShapesRenders simple 2D primitive shapes like circles and polygons
2D Viewport To WorldDemonstrates how to use the Camera::viewport_to_world_2d method with a dynamic viewport and camera.
2D WireframeShowcases wireframes for 2d meshes
Arc 2D MeshesDemonstrates UV-mapping of the circular segment and sector primitives
CPU DrawingManually read/write the pixels of a texture
Custom glTF vertex attribute 2DRenders a glTF mesh in 2D with a custom vertex attribute
Manual Mesh 2DRenders a custom mesh "manually" with "mid-level" renderer apis
Mesh 2DRenders a 2d mesh
Mesh 2D With Vertex ColorsRenders a 2d mesh with vertex color attributes
Mesh2d Alpha ModeUsed to test alpha modes with mesh2d
Mesh2d Repeated TextureShowcase of using uv_transform on the ColorMaterial of a Mesh2d
Move SpriteChanges the transform of a sprite
Multi-Window TextRenders text to multiple windows with different scale factors using both Text and Text2d
Pixel Grid SnappingShows how to create graphics that snap to the pixel grid by rendering to a texture in 2D
SpriteRenders a sprite
Sprite AnimationAnimates a sprite in response to an event
Sprite FlippingRenders a sprite flipped along an axis
Sprite ScaleShows how a sprite can be scaled into a rectangle while keeping the aspect ratio
Sprite SheetRenders an animated sprite
Sprite SliceShowcases slicing sprites into sections that can be scaled independently via the 9-patch technique
Sprite TileRenders a sprite tiled in a grid
Text 2DGenerates text in 2D
Texture AtlasGenerates a texture atlas (sprite sheet) from individual sprites
Tilemap ChunkRenders a tilemap chunk
Transparency in 2DDemonstrates transparency in 2d

3D Rendering

ExampleDescription
3D BloomIllustrates bloom configuration using HDR and emissive materials
3D SceneSimple 3D scene with basic shapes and lighting
3D ShapesA scene showcasing the built-in 3D shapes
3D Viewport To WorldDemonstrates how to use the Camera::viewport_to_world method
Animated MaterialShows how to animate material properties
AnisotropyDisplays an example model with anisotropy
Anti-aliasingCompares different anti-aliasing techniques supported by Bevy
AtmosphereA scene showcasing pbr atmospheric scattering
Atmospheric FogA scene showcasing the atmospheric fog effect
Auto ExposureA scene showcasing auto exposure
Blend ModesShowcases different blend modes
Built-in postprocessingDemonstrates the built-in postprocessing features
Camera sub viewDemonstrates using different sub view effects on a camera
ClearcoatDemonstrates the clearcoat PBR feature
Clustered DecalsDemonstrates clustered decals
Color gradingDemonstrates color grading
DecalDecal rendering
Deferred RenderingRenders meshes with both forward and deferred pipelines
Depth of fieldDemonstrates depth of field
Edit Gltf MaterialShowcases changing materials of a Gltf after Scene spawn
FogA scene showcasing the distance fog effect
Fog volumesDemonstrates fog volumes
Generate Custom MeshSimple showcase of how to generate a custom mesh with a custom texture
Irradiance VolumesDemonstrates irradiance volumes
Light TexturesDemonstrates light textures
LightingIllustrates various lighting options in a simple scene
LightmapsRendering a scene with baked lightmaps
LinesCreate a custom material to draw 3d lines
Load glTFLoads and renders a glTF file as a scene
Load glTF extrasLoads and renders a glTF file as a scene, including the gltf extras
Manual Material ImplementationDemonstrates how to implement a material manually using the mid-level render APIs
Mesh Ray CastDemonstrates ray casting with the MeshRayCast system parameter
MeshletMeshlet rendering for dense high-poly scenes (experimental)
Mixed lightingDemonstrates how to combine baked and dynamic lighting
Motion BlurDemonstrates per-pixel motion blur
Occlusion CullingDemonstration of Occlusion Culling
Order Independent TransparencyDemonstrates how to use OIT
Orthographic ViewShows how to create a 3D orthographic view (for isometric-look in games or CAD applications)
Parallax MappingDemonstrates use of a normal map and depth map for parallax mapping
ParentingDemonstrates parent->child relationships and relative transformations
Percentage-closer soft shadowsDemonstrates percentage-closer soft shadows (PCSS)
Physically Based RenderingDemonstrates use of Physically Based Rendering (PBR) properties
Query glTF primitivesQuery primitives in a glTF scene
Reflection ProbesDemonstrates reflection probes
Render to TextureShows how to render to a texture, useful for mirrors, UI, or exporting images
Rotate Environment MapDemonstrates how to rotate the skybox and the environment map simultaneously
Screen Space Ambient OcclusionA scene showcasing screen space ambient occlusion
Screen Space ReflectionsDemonstrates screen space reflections with water ripples
Scrolling fogDemonstrates how to create the effect of fog moving in the wind
Shadow BiasesDemonstrates how shadow biases affect shadows in a 3d scene
Shadow Caster and ReceiverDemonstrates how to prevent meshes from casting/receiving shadows in a 3d scene
SkyboxLoad a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats.
SolariDemonstrates realtime dynamic raytraced lighting using Bevy Solari.
Specular TintDemonstrates specular tints and maps
Spherical Area LightsDemonstrates how point light radius values affect light behavior
Split ScreenDemonstrates how to render two cameras to the same window to accomplish "split screen"
SpotlightIllustrates spot lights
TextureShows configuration of texture materials
TonemappingCompares tonemapping options
TransmissionShowcases light transmission in the PBR material
Transparency in 3DDemonstrates transparency in 3d
Two PassesRenders two 3d passes to the same window from different perspectives
Update glTF SceneUpdate a scene from a glTF file, either by spawning the scene as a child of another entity, or by accessing the entities of the scene
Vertex ColorsShows the use of vertex colors
Visibility rangeDemonstrates visibility ranges
Volumetric fogDemonstrates volumetric fog and lighting
WireframeShowcases wireframe rendering

Animation

ExampleDescription
Animated MeshPlays an animation on a skinned glTF model of a fox
Animated Mesh ControlPlays an animation from a skinned glTF with keyboard controls
Animated Mesh EventsPlays an animation from a skinned glTF with events
Animated TransformCreate and play an animation defined by code that operates on the Transform component
Animated UIShows how to use animation clips to animate UI properties
Animation EventsDemonstrate how to use animation events
Animation GraphBlends multiple animations together with a graph
Animation MasksDemonstrates animation masks
Color animationDemonstrates how to animate colors using mixing and splines in different color spaces
Custom Skinned MeshSkinned mesh example with mesh and joints data defined in code
Eased MotionDemonstrates the application of easing curves to animate an object
Easing FunctionsShowcases the built-in easing functions
Morph TargetsPlays an animation from a glTF file with meshes with morph targets
glTF Skinned MeshSkinned mesh example with mesh and joints data loaded from a glTF file

Application

ExampleDescription
Advanced log layersIllustrate how to transfer data between log layers and Bevy's ECS
Custom LoopDemonstrates how to create a custom runner (to update an app manually)
Drag and DropAn example that shows how to handle drag and drop in an app
EmptyAn empty application (does nothing)
Empty with DefaultsAn empty application with default plugins
HeadlessAn application that runs without default plugins
Headless RendererAn application that runs with no window, but renders into image file
Log layersIllustrate how to add custom log layers
LogsIllustrate how to use generate log output
No RendererAn application that runs with default plugins and displays an empty window, but without an actual renderer
PluginDemonstrates the creation and registration of a custom plugin
Plugin GroupDemonstrates the creation and registration of a custom plugin group
Return after RunShow how to return to main after the Bevy app has exited
Thread Pool ResourcesCreates and customizes the internal thread pool
Without WinitCreate an application without winit (runs single time, no event loop)

Assets

ExampleDescription
Alter MeshShows how to modify the underlying asset of a Mesh after spawning.
Alter SpriteShows how to modify texture assets after spawning.
Asset DecompressionDemonstrates loading a compressed asset
Asset LoadingDemonstrates various methods to load assets
Asset ProcessingDemonstrates how to process and load custom assets
Asset SettingsDemonstrates various methods of applying settings when loading an asset
Custom AssetImplements a custom asset loader
Custom Asset IOImplements a custom AssetReader
Embedded AssetEmbed an asset in the application binary and load it
Extra Asset SourceLoad an asset from a non-standard asset source
Hot Reloading of AssetsDemonstrates automatic reloading of assets when modified on disk
Multi-asset synchronizationDemonstrates how to wait for multiple assets to be loaded.
Repeated texture configurationHow to configure the texture to repeat instead of the default clamp to edges
Web AssetLoad an asset from the web

Async Tasks

ExampleDescription
Async ComputeHow to use AsyncComputeTaskPool to complete longer running tasks
External Source of Data on an External ThreadHow to use an external thread to run an infinite task and communicate with a channel

Audio

ExampleDescription
AudioShows how to load and play an audio file
Audio ControlShows how to load and play an audio file, and control how it's played
DecodableShows how to create and register a custom audio source by implementing the Decodable type.
PitchShows how to directly play a simple pitch
SoundtrackShows how to play different soundtracks based on game state
Spatial Audio 2DShows how to play spatial audio, and moving the emitter in 2D
Spatial Audio 3DShows how to play spatial audio, and moving the emitter in 3D

Camera

ExampleDescription
2D on Bevy UIShows how to render 2D objects on top of Bevy UI
2D top-down cameraA 2D top-down camera smoothly following player movements
Camera OrbitShows how to orbit a static scene using pitch, yaw, and roll.
Custom ProjectionShows how to create custom camera projections.
First person view modelA first-person camera that uses a world model and a view model with different field of views (FOV)
Projection ZoomShows how to zoom orthographic and perspective projection cameras.
Screen ShakeA simple 2D screen shake effect

Dev tools

ExampleDescription
FPS overlayDemonstrates FPS overlay

Diagnostics

ExampleDescription
Custom DiagnosticShows how to create a custom diagnostic
Enabling/disabling diagnosticShows how to disable/re-enable a Diagnostic during runtime
Log DiagnosticsAdd a plugin that logs diagnostics, like frames per second (FPS), to the console

ECS (Entity Component System)

ExampleDescription
Change DetectionChange detection on components and resources
Component HooksDefine component hooks to manage component lifecycle events
Custom Query ParametersGroups commonly used compound queries and query filters into a single type
Custom ScheduleDemonstrates how to add custom schedules
Dynamic ECSDynamically create components, spawn entities with those components and query those components
ECS GuideFull guide to Bevy's ECS
Entity disablingDemonstrates how to hide entities from the ECS without deleting them
Error handlingHow to return and handle errors across the ECS
EventIllustrates event creation, activation, and reception
Fallible System ParametersSystems are skipped if their parameters cannot be acquired
Fixed TimestepShows how to create systems that run every fixed timestep, rather than every tick
Generic SystemShows how to create systems that can be reused with different types
HierarchyCreates a hierarchy of parents and children entities
Hotpatching SystemsDemonstrates how to hotpatch systems
Immutable ComponentsDemonstrates the creation and utility of immutable components
Iter CombinationsShows how to iterate over combinations of query results
Nondeterministic System OrderSystems run in parallel, but their order isn't always deterministic. Here's how to detect and fix this.
Observer PropagationDemonstrates event propagation with observers
ObserversDemonstrates observers that react to events (both built-in life-cycle events and custom events)
One Shot SystemsShows how to flexibly run systems without scheduling them
Parallel QueryIllustrates parallel queries with ParallelIterator
RelationshipsDefine and work with custom relationships between entities
Removal DetectionQuery for entities that had a specific component removed earlier in the current frame
Run ConditionsRun systems only when one or multiple conditions are met
Send and receive eventsDemonstrates how to send and receive events of the same type in a single system
Startup SystemDemonstrates a startup system (one that runs once when the app starts up)
State ScopedShows how to spawn entities that are automatically despawned either when entering or exiting specific game states.
System ClosureShow how to use closures as systems, and how to configure Local variables by capturing external state
System ParameterIllustrates creating custom system parameters with SystemParam
System PipingPipe the output of one system into a second, allowing you to handle any errors gracefully
System SteppingDemonstrate stepping through systems in order of execution.

Embedded

ExampleDescription
no_std Compatible LibraryExample library compatible with std and no_std targets

Games

ExampleDescription
Alien Cake AddictEat the cakes. Eat them all. An example 3D game
BreakoutAn implementation of the classic game "Breakout".
ContributorsDisplays each contributor as a bouncy bevy-ball!
Desk ToyBevy logo as a desk toy using transparent windows! Now with Googly Eyes!
Game MenuA simple game menu
Loading ScreenDemonstrates how to create a loading screen that waits for all assets to be loaded and render pipelines to be compiled.

Gizmos

ExampleDescription
2D GizmosA scene showcasing 2D gizmos
3D GizmosA scene showcasing 3D gizmos
AxesDemonstrates the function of axes gizmos
Light GizmosA scene showcasing light gizmos

Helpers

ExampleDescription
Camera ControllerExample Free-Cam Styled Camera Controller
WidgetsExample UI Widgets

Input

ExampleDescription
Char Input EventsPrints out all chars as they are inputted
Gamepad InputShows handling of gamepad input, connections, and disconnections
Gamepad Input EventsIterates and prints gamepad input and connection events
Gamepad RumbleShows how to rumble a gamepad using force feedback
Keyboard InputDemonstrates handling a key press/release
Keyboard Input EventsPrints out all keyboard events
Keyboard ModifiersDemonstrates using key modifiers (ctrl, shift)
Mouse GrabDemonstrates how to grab the mouse, locking the cursor to the app's screen
Mouse InputDemonstrates handling a mouse button press/release
Mouse Input EventsPrints out all mouse events (buttons, movement, etc.)
Text InputSimple text input with IME support
Touch InputDisplays touch presses, releases, and cancels
Touch Input EventsPrints out all touch inputs

Math

ExampleDescription
Bounding Volume Intersections (2D)Showcases bounding volumes and intersection tests
Cubic SplinesExhibits different modes of constructing cubic curves using splines
Custom PrimitivesDemonstrates how to add custom primitives and useful traits for them.
Random SamplingDemonstrates how to sample random points from mathematical primitives
Rendering PrimitivesShows off rendering for all math primitives as both Meshes and Gizmos
Sampling PrimitivesDemonstrates all the primitives which can be sampled.
Smooth FollowDemonstrates how to make an entity smoothly follow another using interpolation

Movement

ExampleDescription
Run physics in a fixed timestepHandles input, physics, and rendering in an industry-standard way by using a fixed timestep

Picking

ExampleDescription
Mesh PickingDemonstrates picking meshes
Picking Debug ToolsDemonstrates picking debug overlay
Showcases simple picking events and usageDemonstrates how to use picking events to spawn simple objects
Sprite PickingDemonstrates picking sprites and sprite atlases

Reflection

ExampleDescription
Automatic types registrationDemonstrates how to set up automatic reflect types registration for platforms without inventory support
Custom AttributesRegistering and accessing custom attributes on reflected types
Dynamic TypesHow dynamic types are used with reflection
Function ReflectionDemonstrates how functions can be called dynamically using reflection
Generic ReflectionRegisters concrete instances of generic types that may be used with reflection
ReflectionDemonstrates how reflection in Bevy provides a way to dynamically interact with Rust types
Reflection TypesIllustrates the various reflection types available
Type DataDemonstrates how to create and use type data

Remote Protocol

ExampleDescription
clientA simple command line client that can control Bevy apps via the BRP
serverA Bevy app that you can connect to with the BRP and edit

Scene

ExampleDescription
SceneDemonstrates loading from and saving scenes to files

Shaders

These examples demonstrate how to implement different shaders in user code.

A shader in its most common usage is a small program that is run by the GPU per-vertex in a mesh (a vertex shader) or per-affected-screen-fragment (a fragment shader.) The GPU executes these programs in a highly parallel way.

There are also compute shaders which are used for more general processing leveraging the GPU's parallelism.

ExampleDescription
AnimatedA shader that uses dynamic data like the time since startup
Array TextureA shader that shows how to reuse the core bevy PBR shading functionality in a custom material that obtains the base color from an array texture.
Compute - Game of LifeA compute shader that simulates Conway's Game of Life
Custom Render PhaseShows how to make a complete render phase
Custom Vertex AttributeA shader that reads a mesh's custom vertex attribute
Custom phase itemDemonstrates how to enqueue custom draw commands in a render phase
Extended Bindless MaterialDemonstrates bindless ExtendedMaterial
Extended MaterialA custom shader that builds on the standard material
GPU readbackA very simple compute shader that writes to a buffer that is read by the cpu
InstancingShows that multiple instances of a cube are automatically instanced in one draw call
InstancingA shader that renders a mesh multiple times in one draw call using low level rendering api
MaterialA shader and a material that uses it
MaterialA shader and a material that uses it on a 2d mesh
Material - BindlessDemonstrates how to make materials that use bindless textures
Material - GLSLA shader that uses the GLSL shading language
Material - Screenspace TextureA shader that samples a texture with view-independent UV coordinates
Material - WESLA shader that uses WESL
Material PrepassA shader that uses the various textures generated by the prepass
Post Processing - Custom Render PassA custom post processing effect, using a custom render pass that runs after the main pass
Render Depth to TextureDemonstrates how to use depth-only cameras
Shader DefsA shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader)
Specialized Mesh PipelineDemonstrates how to write a specialized mesh pipeline
Storage BufferA shader that shows how to bind a storage buffer using a custom material.
Texture Binding Array (Bindless Textures)A shader that shows how to bind and sample multiple textures as a binding array (a.k.a. bindless textures).

State

ExampleDescription
Computed StatesAdvanced state patterns using Computed States.
Custom State Transition BehaviorCreating and working with custom state transition schedules.
StatesIllustrates how to use States to control transitioning from a Menu state to an InGame state.
Sub StatesUsing Sub States for hierarchical state handling.

Stress Tests

These examples are used to test the performance and stability of various parts of the engine in an isolated way.

Due to the focus on performance it's recommended to run the stress tests in release mode:

cargo run --release --example <example name>
ExampleDescription
BevymarkA heavy sprite rendering workload to benchmark your system with Bevy
Many Animated MaterialsBenchmark to test rendering many animated materials
Many Animated SpritesDisplays many animated sprites in a grid arrangement with slight offsets to their animation timers. Used for performance testing.
Many ButtonsTest rendering of many UI elements
Many Cameras & LightsTest rendering of many cameras and lights
Many Components (and Entities and Systems)Test large ECS systems
Many CubesSimple benchmark to test per-entity draw overhead. Run with the sphere argument to test frustum culling
Many FoxesLoads an animated fox model and spawns lots of them. Good for testing skinned mesh performance. Takes an unsigned integer argument for the number of foxes to spawn. Defaults to 1000
Many GizmosTest rendering of many gizmos
Many GlyphsSimple benchmark to test text rendering.
Many GradientsStress test for gradient rendering performance
Many LightsSimple benchmark to test rendering many point lights. Run with WGPU_SETTINGS_PRIO=webgl2 to restrict to uniform buffers and max 256 lights
Many SpritesDisplays many sprites in a grid arrangement! Used for performance testing. Use --colored to enable color tinted sprites.
Many Text2dDisplays many Text2d! Used for performance testing.
Text PipelineText Pipeline benchmark
Transform HierarchyVarious test cases for hierarchy and transform propagation performance

Time

ExampleDescription
Time handlingExplains how Time is handled in ECS
TimersIllustrates ticking Timer resources inside systems and handling their state
Virtual timeShows how Time<Virtual> can be used to pause, resume, slow down and speed up a game.

Tools

ExampleDescription
Gamepad ViewerShows a visualization of gamepad buttons, sticks, and triggers
Scene ViewerA simple way to view glTF models with Bevy. Just run cargo run --release --example scene_viewer /path/to/model.gltf#Scene0, replacing the path as appropriate. With no arguments it will load the FieldHelmet glTF model from the repository assets subdirectory

Transforms

ExampleDescription
3D RotationIllustrates how to (constantly) rotate an object around an axis
AlignmentA demonstration of Transform's axis-alignment feature
ScaleIllustrates how to scale an object in each direction
TransformShows multiple transformations of objects
TranslationIllustrates how to move an object along an axis

UI (User Interface)

ExampleDescription
BordersDemonstrates how to create a node with a border
Box ShadowDemonstrates how to create a node with a shadow
ButtonIllustrates creating and updating a button
CSS GridAn example for CSS Grid layout
Core WidgetsDemonstrates use of core (headless) widgets in Bevy UI
Core Widgets (w/Observers)Demonstrates use of core (headless) widgets in Bevy UI, with Observers
Directional NavigationDemonstration of Directional Navigation between UI elements
Display and VisibilityDemonstrates how Display and Visibility work in the UI.
Drag to ScrollThis example tests scale factor, dragging and scrolling
Flex LayoutDemonstrates how the AlignItems and JustifyContent properties can be composed to layout nodes and position text
Font Atlas DebugIllustrates how FontAtlases are populated (used to optimize text rendering internally)
Ghost NodesDemonstrates the use of Ghost Nodes to skip entities in the UI layout hierarchy
GradientsAn example demonstrating gradients
OverflowSimple example demonstrating overflow behavior
Overflow Clip MarginSimple example demonstrating the OverflowClipMargin style property
Overflow and Clipping DebugAn example to debug overflow and clipping behavior
Relative Cursor PositionShowcases the RelativeCursorPosition component
Render UI to TextureAn example of rendering UI as a part of a 3D world
ScrollDemonstrates scrolling UI containers
ScrollbarsDemonstrates use of core scrollbar in Bevy UI
Size ConstraintsDemonstrates how the to use the size constraints to control the size of a UI node.
Stacked GradientsAn example demonstrating stacked gradients
Tab NavigationDemonstration of Tab Navigation between UI elements
TextIllustrates creating and updating text
Text Background ColorsDemonstrates text background colors
Text DebugAn example for debugging text layout
Text Wrap DebugDemonstrates text wrapping
Transparency UIDemonstrates transparency for UI
UI Drag and DropDemonstrates dragging and dropping UI nodes
UI MaterialDemonstrates creating and using custom Ui materials
UI ScalingIllustrates how to scale the UI
UI Target CameraDemonstrates how to use UiTargetCamera and camera ordering.
UI Texture AtlasIllustrates how to use TextureAtlases in UI
UI Texture Atlas SliceIllustrates how to use 9 Slicing for TextureAtlases in UI
UI Texture SliceIllustrates how to use 9 Slicing in UI
UI Texture Slice Flipping and TilingIllustrates how to flip and tile images with 9 Slicing in UI
UI TransformAn example demonstrating how to translate, rotate and scale UI elements.
UI Z-IndexDemonstrates how to control the relative depth (z-position) of UI elements
Viewport DebugAn example for debugging viewport coordinates
Viewport NodeDemonstrates how to create a viewport node with picking support
Virtual KeyboardExample demonstrating a virtual keyboard widget
Window FallthroughIllustrates how to access winit::window::Window's hittest functionality.

Usage

ExampleDescription
Context MenuExample of a context menu
CooldownExample for cooldown on button clicks

Window

ExampleDescription
Clear ColorCreates a solid color window
Custom Cursor ImageDemonstrates creating an animated custom cursor from an image
Custom User EventHandles custom user events within the event loop
Low PowerDemonstrates settings to reduce power use for bevy applications
Monitor infoDisplays information about available monitors (displays).
Multiple WindowsDemonstrates creating multiple windows, and rendering to them
Scale Factor OverrideIllustrates how to customize the default window settings
ScreenshotShows how to save screenshots to disk
Transparent WindowIllustrates making the window transparent and hiding the window decoration
Window Drag MoveDemonstrates drag move and drag resize without window decoration
Window ResizingDemonstrates resizing and responding to resizing a window
Window SettingsDemonstrates customizing default window settings

Tests

ExampleDescription
How to Test AppsHow to test apps (simple integration testing)
How to Test SystemsHow to test systems with commands, queries or resources

Platform-Specific Examples

Android

Setup

rustup target add aarch64-linux-android cargo install cargo-ndk

The Android SDK must be installed, and the environment variable ANDROID_SDK_ROOT set to the root Android sdk folder.

When using NDK (Side by side), the environment variable ANDROID_NDK_ROOT must also be set to one of the NDKs in sdk\ndk\[NDK number].

Alternatively, you can install Android Studio.

Build & Run

To build an Android app, you first need to build shared object files for the target architecture with cargo-ndk:

cargo ndk -t <target_name> -o <project_name>/app/src/main/jniLibs build

For example, to compile to a 64-bit ARM platform:

cargo ndk -t arm64-v8a -o android_example/app/src/main/jniLibs build

Setting the output path ensures the shared object files can be found in target-specific directories under jniLibs where the JNI can find them.

See the cargo-ndk README for other options.

After this you can build it with gradlew:

./gradlew build

Or build it with Android Studio.

Then you can test it in your Android project.

About libc++_shared.so

Bevy may require libc++_shared.so to run on Android, as it is needed by the oboe crate, but typically cargo-ndk does not copy this file automatically.

To include it, you can manually obtain it from NDK source or use a build.rs script for automation, as described in the cargo-ndk README.

Alternatively, you can modify project files to include it when building an APK. To understand the specific steps taken in this project, please refer to the comments within the project files for detailed instructions(app/CMakeList.txt, app/build.gradle, app/src/main/cpp/dummy.cpp).

Debugging

You can view the logs with the following command:

adb logcat | grep 'RustStdoutStderr\|bevy\|wgpu'

In case of an error getting a GPU or setting it up, you can try settings logs of wgpu_hal to DEBUG to get more information.

Sometimes, running the app complains about an unknown activity. This may be fixed by uninstalling the application:

adb uninstall org.bevyengine.example

Old phones

In its examples, Bevy targets the minimum Android API that Play Store requires to upload and update apps. Users of older phones may want to use an older API when testing. By default, Bevy uses GameActivity, which only works for Android API level 31 and higher, so if you want to use older API, you need to switch to NativeActivity.

To use NativeActivity, you need to edit it in cargo.toml manually like this:

bevy = { version = "0.14", default-features = false, features = ["android-native-activity", ...] }

Then build it as the Build & Run section stated above.

About cargo-apk

You can also build an APK with cargo-apk, a simpler and deprecated tool which doesn't support GameActivity. If you want to use this, there is a folder inside the mobile example with instructions.

ExampleFileDescription
androidmobile/src/lib.rsA 3d Scene with a button and playing sound

iOS

Setup

You need to install the correct rust targets:

  • aarch64-apple-ios: iOS devices

  • x86_64-apple-ios: iOS simulator on x86 processors

  • aarch64-apple-ios-sim: iOS simulator on Apple processors

rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim

Build & Run

Using bash:

cd examples/mobile make run

In an ideal world, this will boot up, install and run the app for the first iOS simulator in your xcrun simctl list devices. If this fails, you can specify the simulator device UUID via:

DEVICE_ID=${YOUR_DEVICE_ID} make run

If you'd like to see xcode do stuff, you can run

open bevy_mobile_example.xcodeproj/

which will open xcode. You then must push the zoom zoom play button and wait for the magic.

ExampleFileDescription
iosmobile/src/lib.rsA 3d Scene with a button and playing sound

Wasm

Setup

rustup target add wasm32-unknown-unknown cargo install wasm-bindgen-cli

Build & Run

Following is an example for lighting. For other examples, change the lighting in the following commands.

cargo build --release --example lighting --target wasm32-unknown-unknown wasm-bindgen --out-name wasm_example \ --out-dir examples/wasm/target \ --target web target/wasm32-unknown-unknown/release/examples/lighting.wasm

The first command will build the example for the wasm target, creating a binary. Then, wasm-bindgen-cli is used to create javascript bindings to this wasm file in the output file examples/wasm/target/wasm_example.js, which can be loaded using this example HTML file.

Then serve examples/wasm directory to browser. i.e.

## cargo install basic-http-server basic-http-server examples/wasm ## with python python3 -m http.server --directory examples/wasm ## with ruby ruby -run -ehttpd examples/wasm
WebGL2 and WebGPU

Bevy support for WebGPU is being worked on, but is currently experimental.

To build for WebGPU, you'll need to enable the webgpu feature. This will override the webgl2 feature, and builds with the webgpu feature enabled won't be able to run on browsers that don't support WebGPU.

Bevy has a helper to build its examples:

  • Build for WebGL2: cargo run -p build-wasm-example -- --api webgl2 load_gltf

  • Build for WebGPU: cargo run -p build-wasm-example -- --api webgpu load_gltf

  • Debug: cargo run -p build-wasm-example -- --debug --api webgl2 load_gltf

This helper will log the command used to build the examples.

Audio in the browsers

For the moment, everything is single threaded, this can lead to stuttering when playing audio in browsers. Not all browsers react the same way for all games, you will have to experiment for your game.

In browsers, audio is not authorized to start without being triggered by an user interaction. This is to avoid multiple tabs all starting to auto play some sounds. You can find more context and explanation for this on Google Chrome blog. This page also describes a JS workaround to resume audio as soon as the user interact with your game.

Optimizing

On the web, it's useful to reduce the size of the files that are distributed. With rust, there are many ways to improve your executable sizes, starting with the steps described in the quick-start guide.

Now, when building the executable, use --profile wasm-release instead of --release:

cargo build --profile wasm-release --example lighting --target wasm32-unknown-unknown

To apply wasm-opt, first locate the .wasm file generated in the --out-dir of the earlier wasm-bindgen-cli command (the filename should end with _bg.wasm), then run:

wasm-opt -Oz --output optimized.wasm examples/wasm/target/lighting_bg.wasm mv optimized.wasm examples/wasm/target/lighting_bg.wasm

Make sure your final executable size is actually smaller. Some optimizations may not be worth keeping due to compilation time increases.

For a small project with a basic 3d model and two lights, the generated file sizes are, as of July 2022, as follows:

profilewasm-optno wasm-opt
Default8.5M13.0M
opt-level = "z"6.1M12.7M
"z" + lto = "thin"5.9M12M
"z" + lto = "fat"5.1M9.4M
"z" + "thin" + codegen-units = 15.3M11M
"z" + "fat" + codegen-units = 14.8M8.5M

Loading Assets

To load assets, they need to be available in the folder examples/wasm/assets. Cloning this repository will set it up as a symlink on Linux and macOS, but you will need to manually move the assets on Windows.