Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/3d/3d_viewport_to_world.rs
6592 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 at what distance the ray is hitting the ground plane.
25
&& let Some(distance) =
26
ray.intersect_plane(ground.translation(), InfinitePlane3d::new(ground.up()))
27
{
28
let point = ray.get_point(distance);
29
30
// Draw a circle just above the ground plane at that position.
31
gizmos.circle(
32
Isometry3d::new(
33
point + ground.up() * 0.01,
34
Quat::from_rotation_arc(Vec3::Z, ground.up().as_vec3()),
35
),
36
0.2,
37
Color::WHITE,
38
);
39
}
40
}
41
42
#[derive(Component)]
43
struct Ground;
44
45
fn setup(
46
mut commands: Commands,
47
mut meshes: ResMut<Assets<Mesh>>,
48
mut materials: ResMut<Assets<StandardMaterial>>,
49
) {
50
// plane
51
commands.spawn((
52
Mesh3d(meshes.add(Plane3d::default().mesh().size(20., 20.))),
53
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
54
Ground,
55
));
56
57
// light
58
commands.spawn((
59
DirectionalLight::default(),
60
Transform::from_translation(Vec3::ONE).looking_at(Vec3::ZERO, Vec3::Y),
61
));
62
63
// camera
64
commands.spawn((
65
Camera3d::default(),
66
Transform::from_xyz(15.0, 5.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
67
));
68
}
69
70