simple_picking/
simple_picking.rs1use bevy::prelude::*;
4
5fn main() {
6 App::new()
7 .add_plugins((DefaultPlugins, MeshPickingPlugin))
8 .add_systems(Startup, setup_scene)
9 .run();
10}
11
12fn setup_scene(
13 mut commands: Commands,
14 mut meshes: ResMut<Assets<Mesh>>,
15 mut materials: ResMut<Assets<StandardMaterial>>,
16) {
17 commands
18 .spawn((
19 Text::new("Click Me to get a box\nDrag cubes to rotate"),
20 Node {
21 position_type: PositionType::Absolute,
22 top: percent(12),
23 left: percent(12),
24 ..default()
25 },
26 ))
27 .observe(on_click_spawn_cube)
28 .observe(|out: On<Pointer<Out>>, mut texts: Query<&mut TextColor>| {
29 let mut text_color = texts.get_mut(out.entity).unwrap();
30 text_color.0 = Color::WHITE;
31 })
32 .observe(
33 |over: On<Pointer<Over>>, mut texts: Query<&mut TextColor>| {
34 let mut color = texts.get_mut(over.entity).unwrap();
35 color.0 = bevy::color::palettes::tailwind::CYAN_400.into();
36 },
37 );
38
39 commands.spawn((
41 Mesh3d(meshes.add(Circle::new(4.0))),
42 MeshMaterial3d(materials.add(Color::WHITE)),
43 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
44 ));
45
46 commands.spawn((
48 PointLight {
49 shadows_enabled: true,
50 ..default()
51 },
52 Transform::from_xyz(4.0, 8.0, 4.0),
53 ));
54
55 commands.spawn((
57 Camera3d::default(),
58 Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
59 ));
60}
61
62fn on_click_spawn_cube(
63 _click: On<Pointer<Click>>,
64 mut commands: Commands,
65 mut meshes: ResMut<Assets<Mesh>>,
66 mut materials: ResMut<Assets<StandardMaterial>>,
67 mut num: Local<usize>,
68) {
69 commands
70 .spawn((
71 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
72 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
73 Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0),
74 ))
75 .observe(on_drag_rotate);
77 *num += 1;
78}
79
80fn on_drag_rotate(drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>) {
81 if let Ok(mut transform) = transforms.get_mut(drag.entity) {
82 transform.rotate_y(drag.delta.x * 0.02);
83 transform.rotate_x(drag.delta.y * 0.02);
84 }
85}