get cursor position

This commit is contained in:
Magnus von Wachenfeldt 2022-08-15 21:17:32 +02:00
parent 8391811448
commit a8e204e60c
Signed by: magnus
GPG Key ID: A469F7D71D09F795
2 changed files with 34 additions and 2 deletions

View File

@ -3,6 +3,7 @@ use std::{collections::HashMap, net::UdpSocket, time::SystemTime};
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
prelude::*,
render::camera::RenderTarget,
};
use bevy_egui::{EguiContext, EguiPlugin};
@ -18,6 +19,9 @@ use daggmask_shared::{
use renet_visualizer::{RenetClientVisualizer, RenetVisualizerStyle};
#[derive(Component)]
struct MainCamera;
#[derive(Component)]
struct ControlledPlayer;
@ -77,6 +81,7 @@ fn main() {
app.insert_resource(NetworkMapping::default());
app.add_system(player_input);
app.add_system(cursor_system);
app.add_system(client_send_input.with_run_criteria(run_if_client_connected));
app.add_system(client_send_player_commands.with_run_criteria(run_if_client_connected));
app.add_system(client_sync_players.with_run_criteria(run_if_client_connected));
@ -133,6 +138,30 @@ fn player_input(
}
}
fn cursor_system(
wnds: Res<Windows>,
q_camera: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
) {
let (camera, camera_transform) = q_camera.single();
let wnd = if let RenderTarget::Window(id) = camera.target {
wnds.get(id).unwrap()
} else {
wnds.get_primary().unwrap()
};
// check if the cursor is inside the window and get its position
if let Some(screen_pos) = wnd.cursor_position() {
let window_size = Vec2::new(wnd.width() as f32, wnd.height() as f32);
let ndc = (screen_pos / window_size) * 2.0 - Vec2::ONE;
let ndc_to_world = camera_transform.compute_matrix() * camera.projection_matrix().inverse();
let world_pos = ndc_to_world.project_point3(ndc.extend(-1.0));
let world_pos: Vec2 = world_pos.truncate();
info!("World coords: {}/{}", world_pos.x, world_pos.y);
}
}
fn client_send_input(player_input: Res<PlayerInput>, mut client: ResMut<RenetClient>) {
let input_message = bincode::serialize(&*player_input).unwrap();
@ -247,5 +276,7 @@ fn client_sync_players(
}
fn setup_camera(mut commands: Commands) {
commands.spawn_bundle(Camera2dBundle::default());
commands
.spawn_bundle(Camera2dBundle::default())
.insert(MainCamera);
}

View File

@ -6,7 +6,8 @@ use bevy::{
};
use bevy_egui::{EguiContext, EguiPlugin};
use bevy_rapier2d::{prelude::*, rapier::prelude::CollisionEventFlags};
use bevy_rapier2d::prelude::*;
use bevy_renet::{
renet::{RenetServer, ServerAuthentication, ServerConfig, ServerEvent},
RenetServerPlugin,