forked from aevyrie/bevy_mod_raycast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimal_deferred.rs
57 lines (50 loc) · 2.15 KB
/
minimal_deferred.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
//! This example demonstrates how to use the [`bevy_mod_raycast::deferred`]` API. Unlike the
//! [`Raycast`] system param, this API is declarative, and does not return a result immediately.
//! Instead, behavior is defined using components, and raycasting is done once per frame.
use bevy::prelude::*;
use bevy_mod_raycast::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(DeferredRaycastingPlugin::<MyRaycastSet>::default())
// Overrides default settings and enables the debug cursor
.insert_resource(RaycastPluginState::<MyRaycastSet>::default().with_debug_cursor())
.add_systems(Startup, setup)
.add_systems(Update, move_ray)
.run();
}
const DIST: Vec3 = Vec3::new(0.0, 0.0, -7.0);
#[derive(Reflect)]
struct MyRaycastSet; // Groups raycast sources with meshes, can use `()` instead.
#[derive(Component)]
struct MovingRaycaster;
fn move_ray(time: Res<Time>, mut query: Query<&mut Transform, With<MovingRaycaster>>) {
let t = time.elapsed_seconds();
let pos = Vec3::new(t.sin(), (t * 1.5).cos() * 2.0, t.cos()) * 1.5 + DIST;
let dir = (DIST - pos).normalize();
*query.single_mut() = Transform::from_translation(pos).looking_to(dir, Vec3::Y);
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn(Camera3dBundle::default());
commands.spawn(PointLightBundle::default());
// Unlike the immediate mode API where the raycast is built every frame in a system, instead we
// spawn an entity and mark it as a raycasting source, using its `GlobalTransform`.
commands.spawn((
MovingRaycaster,
SpatialBundle::default(),
RaycastSource::<MyRaycastSet>::new_transform_empty(),
));
commands.spawn((
PbrBundle {
mesh: meshes.add(Mesh::try_from(shape::Capsule::default()).unwrap()),
material: materials.add(Color::rgb(1.0, 1.0, 1.0).into()),
transform: Transform::from_translation(DIST),
..default()
},
RaycastMesh::<MyRaycastSet>::default(), // Make this mesh ray cast-able
));
}