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.
Smooth Follow
An entity that smoothly follows a target position using interpolation.
Introduction
Smooth following uses exponential decay to move an entity toward a target. Instead of snapping instantly, the entity moves faster when far away and slower when close, creating a natural easing effect.
from pybevy.prelude import *
import mathComponents
@component
class Follower(Component):
pass
@component
class Target(Component):
passSetup
def setup(commands: Commands, meshes: ResMut[Assets[Mesh]], materials: ResMut[Assets[StandardMaterial]]) -> None:
commands.spawn(
Target(),
Mesh3d(meshes.add(Sphere(0.3))),
MeshMaterial3d(materials.add(Color.srgb(1.0, 0.3, 0.3))),
)
commands.spawn(
Follower(),
Mesh3d(meshes.add(Cuboid.from_length(0.5))),
MeshMaterial3d(materials.add(Color.srgb(0.3, 0.3, 1.0))),
)
commands.spawn(PointLight(shadows_enabled=True), Transform.from_xyz(4.0, 8.0, 4.0))
commands.spawn(Camera3d(), Transform.from_xyz(0.0, 5.0, 10.0).looking_at(Vec3.ZERO, Vec3.Y))Movement Systems
def move_target(time: Res[Time], query: Query[Mut[Transform], With[Target]]) -> None:
t = time.elapsed_secs()
for transform in query:
transform.translation.x = math.sin(t) * 3.0
transform.translation.z = math.cos(t * 0.7) * 3.0
@resource
class TargetPosition(Resource):
def __init__(self):
self.x = 0.0
self.z = 0.0
def update_target_position(targets: Query[Transform, With[Target]], pos: ResMut[TargetPosition]) -> None:
for t in targets:
pos.x = t.translation.x
pos.z = t.translation.z
def follow_target(
time: Res[Time],
pos: Res[TargetPosition],
followers: Query[Mut[Transform], With[Follower]],
) -> None:
for follower_transform in followers:
decay = 1.0 - math.exp(-3.0 * time.delta_secs())
follower_transform.translation.x += (pos.x - follower_transform.translation.x) * decay
follower_transform.translation.z += (pos.z - follower_transform.translation.z) * decayRunning the App
@entrypoint
def main(app: App) -> App:
return (
app
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.insert_resource(TargetPosition())
.add_systems(Update, (move_target, update_target_position, follow_target))
)
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.
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.