Path: blob/main/examples/async_tasks/external_source_external_thread.rs
6593 views
//! How to use an external thread to run an infinite task and communicate with a channel.12use bevy::prelude::*;3// Using crossbeam_channel instead of std as std `Receiver` is `!Sync`4use crossbeam_channel::{bounded, Receiver};5use rand::{Rng, SeedableRng};6use rand_chacha::ChaCha8Rng;78fn main() {9App::new()10.add_event::<StreamEvent>()11.add_plugins(DefaultPlugins)12.add_systems(Startup, setup)13.add_systems(Update, (spawn_text, move_text))14.add_systems(FixedUpdate, read_stream)15.insert_resource(Time::<Fixed>::from_seconds(0.5))16.run();17}1819#[derive(Resource, Deref)]20struct StreamReceiver(Receiver<u32>);2122#[derive(BufferedEvent)]23struct StreamEvent(u32);2425fn setup(mut commands: Commands) {26commands.spawn(Camera2d);2728let (tx, rx) = bounded::<u32>(1);29std::thread::spawn(move || {30// We're seeding the PRNG here to make this example deterministic for testing purposes.31// This isn't strictly required in practical use unless you need your app to be deterministic.32let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);33loop {34// Everything here happens in another thread35// This is where you could connect to an external data source3637// This will block until the previous value has been read in system `read_stream`38tx.send(rng.random_range(0..2000)).unwrap();39}40});4142commands.insert_resource(StreamReceiver(rx));43}4445// This system reads from the receiver and sends events to Bevy46fn read_stream(receiver: Res<StreamReceiver>, mut events: EventWriter<StreamEvent>) {47for from_stream in receiver.try_iter() {48events.write(StreamEvent(from_stream));49}50}5152fn spawn_text(mut commands: Commands, mut reader: EventReader<StreamEvent>) {53for (per_frame, event) in reader.read().enumerate() {54commands.spawn((55Text2d::new(event.0.to_string()),56TextLayout::new_with_justify(Justify::Center),57Transform::from_xyz(per_frame as f32 * 100.0, 300.0, 0.0),58));59}60}6162fn move_text(63mut commands: Commands,64mut texts: Query<(Entity, &mut Transform), With<Text2d>>,65time: Res<Time>,66) {67for (entity, mut position) in &mut texts {68position.translation -= Vec3::new(0.0, 100.0 * time.delta_secs(), 0.0);69if position.translation.y < -300.0 {70commands.entity(entity).despawn();71}72}73}747576