📄
src/bunny.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use bevy::{ app::{App, Startup, Update}, asset::AssetServer, ecs::{ component::Component, query::{With, Without}, system::{Commands, Query, Res, Single}, }, gltf::GltfAssetLabel, math::Vec3, scene::SceneRoot, time::Time, transform::components::Transform, }; use crate::dog::Dog; pub trait BunnySystems { fn add_bunny_systems(&mut self) -> &mut Self; } impl BunnySystems for App { fn add_bunny_systems(&mut self) -> &mut Self { self.add_systems(Startup, setup) .add_systems(Update, control) } } #[derive(Component, Default)] struct Bunny; const DETECTION_DISTANCE: f32 = 2.5; const SPEED: f32 = 10.0; fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let model = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animal-bunny.glb")); commands.spawn(( SceneRoot(model.clone()), Transform::from_xyz(5.0, 0.0, 0.0), Bunny::default(), )); commands.spawn(( SceneRoot(model.clone()), Transform::from_xyz(-5.0, 0.0, 0.0), Bunny::default(), )); } fn control( time: Res<Time>, dog: Single<&Transform, (With<Dog>, Without<Bunny>)>, bunnies: Query<&mut Transform, With<Bunny>>, ) { for mut bunny in bunnies { let direction = bunny.translation - dog.translation; if direction.length_squared() < DETECTION_DISTANCE * DETECTION_DISTANCE { bunny.look_to(-direction, Vec3::Y); bunny.translation += direction.normalize() * SPEED * time.delta_secs(); } } }