protocol.rs (2077B)
1 use derive_more::{Add, Mul}; 2 3 use bevy::prelude::*; 4 use lightyear::prelude::*; 5 use serde::{Deserialize, Serialize}; 6 7 #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] 8 pub struct Direction { 9 pub(crate) up: bool, 10 pub(crate) down: bool, 11 pub(crate) left: bool, 12 pub(crate) right: bool, 13 } 14 15 impl Direction { 16 pub(crate) fn is_none(&self) -> bool { 17 !self.up && !self.down && !self.left && !self.right 18 } 19 } 20 21 #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] 22 pub enum Inputs { 23 Direction(Direction), 24 Delete, 25 Spawn, 26 // NOTE: we NEED to provide a None input so that the server can distinguish between lost input packets and 'None' inputs 27 None, 28 } 29 impl UserAction for Inputs {} 30 31 #[derive(Message, Serialize, Deserialize, Clone, Debug, PartialEq)] 32 pub struct Message1(pub usize); 33 34 #[message_protocol(protocol = "MatrixRPGGameProto")] 35 pub enum Messages { 36 Message1(Message1), 37 } 38 39 #[derive(Component, Message, Serialize, Deserialize, Clone, Debug, PartialEq)] 40 pub struct PlayerId(pub ClientId); 41 42 // `Deref` and `DerefMut` are from bevy 43 // `Add` and `Mul` are from the derive_more crate 44 #[derive( 45 Component, Message, Serialize, Deserialize, Clone, Debug, PartialEq, Deref, DerefMut, Add, Mul, 46 )] 47 pub struct PlayerPosition(pub Vec2); 48 49 impl std::ops::Mul<f32> for &PlayerPosition { 50 type Output = PlayerPosition; 51 52 fn mul(self, rhs: f32) -> Self::Output { 53 PlayerPosition(self.0 * rhs) 54 } 55 } 56 57 #[component_protocol(protocol = "MatrixRPGGameProto")] 58 pub enum Components { 59 #[sync(once)] 60 PlayerId(PlayerId), 61 #[sync(full)] 62 PlayerPosition(PlayerPosition), 63 } 64 65 #[derive(Channel)] 66 pub struct Channel1; 67 68 protocolize! { 69 Self = MatrixRPGGameProto, 70 Message = Messages, 71 Component = Components, 72 Input = Inputs, 73 } 74 75 pub(crate) fn protocol() -> MatrixRPGGameProto { 76 let mut protocol = MatrixRPGGameProto::default(); 77 protocol.add_channel::<Channel1>(ChannelSettings { 78 mode: ChannelMode::OrderedReliable(ReliableSettings::default()), 79 ..default() 80 }); 81 protocol 82 }