diff options
author | Alexander Foremny <aforemny@posteo.de> | 2024-03-14 06:43:53 +0100 |
---|---|---|
committer | Alexander Foremny <aforemny@posteo.de> | 2024-03-15 02:50:57 +0100 |
commit | 69584a302d132dc2bcc3837437e7347a3e0a5114 (patch) | |
tree | fae29ea706451e91a0dee99200fa661b78de3517 /src/client.rs | |
parent | 9671dd79163e654f61896ec4f61142a71c2f82c0 (diff) |
feat: players can teleport
Diffstat (limited to 'src/client.rs')
-rw-r--r-- | src/client.rs | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..b36bba9 --- /dev/null +++ b/src/client.rs @@ -0,0 +1,82 @@ +use crate::client::network::*; +use crate::protocol::*; +use crate::shared::*; +use bevy::input::mouse::MouseButton; +use bevy::prelude::*; +use bevy::sprite::{MaterialMesh2dBundle, Mesh2dHandle}; +use lightyear::client::input::InputSystemSet; +use lightyear::prelude::*; + +mod network; + +pub fn main(transport: TransportConfig) { + App::new() + .add_plugins(DefaultPlugins) + .add_plugins(ClientPlugin { transport }) + .run(); +} + +struct ClientPlugin { + pub transport: TransportConfig, +} + +impl Plugin for ClientPlugin { + fn build(&self, app: &mut App) { + app.add_plugins(NetworkPlugin { + transport: self.transport.clone(), + }) + .add_systems(Startup, setup) + .add_systems(Update, spawn_players) + .add_systems(Update, move_players) + .add_systems( + FixedPreUpdate, + buffer_input.in_set(InputSystemSet::BufferInputs), + ); + } +} + +fn setup(mut client: ClientMut, mut commands: Commands) { + commands.spawn(Camera2dBundle::default()); + client.connect().unwrap(); +} + +fn spawn_players( + mut commands: Commands, + mut materials: ResMut<Assets<ColorMaterial>>, + mut meshes: ResMut<Assets<Mesh>>, + players: Query<(Entity, &PlayerPosition, &PlayerColor), Added<PlayerId>>, +) { + for (entity, position, color) in players.iter() { + commands.entity(entity).insert(MaterialMesh2dBundle { + mesh: Mesh2dHandle(meshes.add(Circle { radius: 10. })), + material: materials.add(color.0), + transform: Transform::from_xyz(position.0.x, position.0.y, 0.), + ..Default::default() + }); + } +} + +fn move_players(mut players: Query<(&mut Transform, &PlayerPosition), Changed<PlayerPosition>>) { + for (mut transform, player_position) in players.iter_mut() { + transform.translation = Vec3::new(player_position.0.x, player_position.0.y, 0.); + } +} + +fn buffer_input( + cameras: Query<(&Camera, &GlobalTransform)>, + mouse_input: Res<ButtonInput<MouseButton>>, + mut client: ClientMut, + windows: Query<&Window>, +) { + let window = windows.single(); + let (camera, camera_transform) = cameras.single(); + if mouse_input.just_pressed(MouseButton::Left) { + if let Some(cursor_position) = window.cursor_position() { + if let Some(world_position) = + camera.viewport_to_world_2d(camera_transform, cursor_position) + { + client.add_input(Inputs::Teleport(world_position)); + } + } + } +} |