⚠️ Beta State

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.

Move Sprite

A sprite that moves back and forth across the screen.

Introduction

This example shows how to move a sprite by modifying its Transform each frame. A custom Direction component tracks whether the sprite is moving left or right.

from pybevy.prelude import *

Direction Component

We define a simple component to track the sprite's movement direction.

@component
class Direction(Component):
    LEFT: int = 0
    RIGHT: int = 1

Setup

Spawn a camera, load a sprite image, and give the sprite an initial direction.

def setup(commands: Commands, asset_server: AssetServer) -> None:
    commands.spawn(Camera2d())
    direction = Direction()
    direction.RIGHT = True
    direction.LEFT = False
    commands.spawn(
        Sprite.from_image(asset_server.load_image("branding/icon.png")),
        Transform.from_xyz(0.0, 0.0, 0.0),
        direction,
    )

Movement System

Each frame, move the sprite based on its direction. Reverse direction when hitting a boundary.

def sprite_movement(
    time: Res[Time], sprite_query: Query[tuple[Mut[Direction], Mut[Transform]]]
) -> None:
    for direction, transform in sprite_query:
        if direction.RIGHT:
            transform.translation.x += 150.0 * time.delta_secs()
        else:
            transform.translation.x -= 150.0 * time.delta_secs()
 
        if transform.translation.x > 200.0:
            direction.LEFT = True
            direction.RIGHT = False
        elif transform.translation.x < -200.0:
            direction.LEFT = False
            direction.RIGHT = True

Running the App

@entrypoint
def main(app: App) -> App:
    return (
        app
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, sprite_movement)
    )
 
if __name__ == "__main__":
    main().run()

Running this example

Use PyBevy's hot reload feature to run and develop this example. If you don't have PyBevy installed, check out the Quick Start guide.

$pybevy watch move_sprite.py

The code will reload automatically when you make changes to the file.


From Python to Rust

Notice how the core concepts in the code—Commands, Assets, App, and Systems—are identical to the original Bevy example?

This is the power of pybevy! It lets you learn Bevy's powerful, data-driven architecture in friendly Python.

When your project grows and you're ready for maximum, native performance, you'll already know the concepts to start writing systems in Bevy Engine with Rust.