docs/bevy/examples/dev_tools/infinite_grid.rs 2.6 K · 88 lines · raw · history

1 //! A simple example to show how to spawn an infinite grid.
2 //!
3 //! Infinite grids are useful as the ground plane in editor-like applications,
4 //! as they provide a consistent reference for the orientation of objects
5 //! and an evenly spaced grid to judge relative scale.
6
7 use bevy::{
8 camera_controller::free_camera::{FreeCamera, FreeCameraPlugin},
9 dev_tools::infinite_grid::{InfiniteGrid, InfiniteGridPlugin, InfiniteGridSettings},
10 prelude::*,
11 };
12
13 fn main() {
14 App::new()
15 .add_plugins((
16 DefaultPlugins,
17 FreeCameraPlugin,
18 // Make sure to add the plugin
19 InfiniteGridPlugin,
20 ))
21 .add_systems(Startup, setup_system)
22 .add_systems(Update, toggle_visibility)
23 .run();
24 }
25
26 fn setup_system(
27 mut commands: Commands,
28 mut meshes: ResMut<Assets<Mesh>>,
29 mut standard_materials: ResMut<Assets<StandardMaterial>>,
30 ) {
31 commands.spawn((
32 // You need to spawn an entity with this component
33 InfiniteGrid,
34 // Optional component you can use to configure the grid
35 InfiniteGridSettings::default(),
36 ));
37
38 commands.spawn((
39 Camera3d::default(),
40 Transform::from_xyz(-12.5, 5.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
41 FreeCamera::default(),
42 ));
43
44 commands.spawn((
45 DirectionalLight { ..default() },
46 Transform::from_translation(Vec3::X * 15. + Vec3::Y * 20.).looking_at(Vec3::ZERO, Vec3::Y),
47 ));
48
49 // cube
50 commands.spawn((
51 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
52 MeshMaterial3d(
53 standard_materials.add(StandardMaterial::from_color(Color::srgba(
54 1.0, 1.0, 1.0, 0.5,
55 ))),
56 ),
57 Transform::from_xyz(0.0, 2.0, 0.0),
58 ));
59
60 commands.spawn((
61 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
62 MeshMaterial3d(
63 standard_materials.add(StandardMaterial::from_color(Color::srgba(
64 1.0, 1.0, 1.0, 0.5,
65 ))),
66 ),
67 Transform::from_xyz(0.0, -2.0, 0.0),
68 ));
69 }
70
71 fn toggle_visibility(
72 query: Single<(&mut Visibility, &InheritedVisibility), With<InfiniteGrid>>,
73 input: Res<ButtonInput<KeyCode>>,
74 ) {
75 let (mut visibility, inherited_visibility) = query.into_inner();
76
77 // Toggle infinite plane visibility by pressing 'P'
78 if input.just_pressed(KeyCode::KeyP) {
79 match inherited_visibility.get() {
80 true => {
81 *visibility = Visibility::Hidden;
82 }
83 false => {
84 *visibility = Visibility::Visible;
85 }
86 }
87 }
88 }