Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/3d/3d_viewport_to_world.rs
9471 views
1
//! This example demonstrates how to use the `Camera::viewport_to_world` method.
2
3
use bevy::prelude::*;
4
5
fn main() {
6
App::new()
7
.add_plugins(DefaultPlugins)
8
.add_systems(Startup, setup)
9
.add_systems(Update, draw_cursor)
10
.run();
11
}
12
13
fn draw_cursor(
14
camera_query: Single<(&Camera, &GlobalTransform)>,
15
ground: Single<&GlobalTransform, With<Ground>>,
16
window: Single<&Window>,
17
mut gizmos: Gizmos,
18
) {
19
let (camera, camera_transform) = *camera_query;
20
21
if let Some(cursor_position) = window.cursor_position()
22
// Calculate a ray pointing from the camera into the world based on the cursor's position.
23
&& let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position)
24
// Calculate if and where the ray is hitting the ground plane.
25
&& let Some(point) = ray.plane_intersection_point(ground.translation(), InfinitePlane3d::new(ground.up()))
26
{
27
// Draw a circle just above the ground plane at that position.
28
gizmos.circle(
29
Isometry3d::new(
30
point + ground.up() * 0.01,
31
Quat::from_rotation_arc(Vec3::Z, ground.up().as_vec3()),
32
),
33
0.2,
34
Color::WHITE,
35
);
36
}
37
}
38
39
#[derive(Component)]
40
struct Ground;
41
42
fn setup(
43
mut commands: Commands,
44
mut meshes: ResMut<Assets<Mesh>>,
45
mut materials: ResMut<Assets<StandardMaterial>>,
46
) {
47
// plane
48
commands.spawn((
49
Mesh3d(meshes.add(Plane3d::default().mesh().size(20., 20.))),
50
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
51
Ground,
52
));
53
54
// light
55
commands.spawn((
56
DirectionalLight::default(),
57
Transform::from_translation(Vec3::ONE).looking_at(Vec3::ZERO, Vec3::Y),
58
));
59
60
// camera
61
commands.spawn((
62
Camera3d::default(),
63
Transform::from_xyz(15.0, 5.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
64
));
65
}
66
67