Create generic distribution system
Still incredibly basic and only handles initial distribution and spawning with no relationships or anything.
This commit is contained in:
parent
d76afe92f0
commit
4db82f328b
5 changed files with 66 additions and 8 deletions
49
src/net/distribution.rs
Normal file
49
src/net/distribution.rs
Normal file
|
@ -0,0 +1,49 @@
|
|||
use bevy::prelude::*;
|
||||
|
||||
use super::{
|
||||
packet::{InboundPacket, OutboundPacket, Packet},
|
||||
peer::Peer,
|
||||
state::NetworkState,
|
||||
};
|
||||
|
||||
fn spawner<T: TryFrom<Vec<u8>> + Component>(
|
||||
mut inbound: EventReader<InboundPacket>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for packet in inbound.read() {
|
||||
if let Ok(entity) = T::try_from(packet.0.message.clone()) {
|
||||
commands.spawn(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sender<T: Into<Vec<u8>> + Component + Clone>(
|
||||
peers: Query<&Peer, Added<Peer>>,
|
||||
entities: Query<&T>,
|
||||
mut outbound: EventWriter<OutboundPacket>,
|
||||
) {
|
||||
for peer in peers {
|
||||
for entity in entities {
|
||||
outbound.write(OutboundPacket(Packet::new(
|
||||
(*entity).clone().into(),
|
||||
peer.uuid,
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Networked: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone {
|
||||
fn register(app: &mut App);
|
||||
}
|
||||
|
||||
impl<T> Networked for T
|
||||
where
|
||||
T: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone,
|
||||
{
|
||||
fn register(app: &mut App) {
|
||||
app.add_systems(
|
||||
FixedUpdate,
|
||||
(sender::<T>, spawner::<T>).run_if(in_state(NetworkState::MultiPlayer)),
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue