mirror of
https://github.com/bevyengine/bevy
synced 2025-02-16 14:08:32 +00:00
# Objective
- Fix error when closing window in 2d_viewport_to_world example.
Before
```
2024-08-17T22:51:47.690252Z INFO bevy_winit::system: Creating new window "App" (0v1#4294967296)
2024-08-17T22:52:22.062959Z INFO bevy_window::system: No windows are open, exiting
2024-08-17T22:52:22.064045Z INFO bevy_winit::system: Closing window 0v1#4294967296
thread 'Compute Task Pool (5)' panicked at examples/2d/2d_viewport_to_world.rs:20:41:
called `Result::unwrap()` on an `Err` value: NoEntities("bevy_ecs::query::state::QueryState<&bevy_window:🪟:Window>")
```
After
```
2024-08-17T22:57:31.623499Z INFO bevy_winit::system: Creating new window "App" (0v1#4294967296)
2024-08-17T22:57:32.990058Z INFO bevy_window::system: No windows are open, exiting
2024-08-17T22:57:32.991152Z INFO bevy_winit::system: Closing window 0v1#4294967296
2024-08-17T22:57:32.994426Z INFO bevy_window::system: No windows are open, exiting
* Terminal will be reused by tasks, press any key to close it.
```
## Solution
- Check if the window still exists before drawing the cursor
38 lines
962 B
Rust
38 lines
962 B
Rust
//! This example demonstrates how to use the `Camera::viewport_to_world_2d` method.
|
|
|
|
use bevy::{color::palettes::basic::WHITE, prelude::*};
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_systems(Startup, setup)
|
|
.add_systems(Update, draw_cursor)
|
|
.run();
|
|
}
|
|
|
|
fn draw_cursor(
|
|
camera_query: Query<(&Camera, &GlobalTransform)>,
|
|
windows: Query<&Window>,
|
|
mut gizmos: Gizmos,
|
|
) {
|
|
let (camera, camera_transform) = camera_query.single();
|
|
|
|
let Ok(window) = windows.get_single() else {
|
|
return;
|
|
};
|
|
|
|
let Some(cursor_position) = window.cursor_position() else {
|
|
return;
|
|
};
|
|
|
|
// Calculate a world position based on the cursor's position.
|
|
let Some(point) = camera.viewport_to_world_2d(camera_transform, cursor_position) else {
|
|
return;
|
|
};
|
|
|
|
gizmos.circle_2d(point, 10., WHITE);
|
|
}
|
|
|
|
fn setup(mut commands: Commands) {
|
|
commands.spawn(Camera2dBundle::default());
|
|
}
|