~starkingdoms/starkingdoms

ref: 42f762da6cbfb717018fc435533ed423fe54b331 starkingdoms/crates/unified/src/server/player.rs -rw-r--r-- 2.0 KiB
42f762da — core planets and hearty 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use bevy::prelude::*;
use bevy_rapier2d::prelude::{AdditionalMassProperties, Collider, MassProperties, ReadMassProperties, RigidBody};
use bevy_replicon::prelude::{ConnectedClient, Replicated};
use crate::config::planet::Planet;
use crate::ecs::{Part, PartBundle, Player};
use crate::server::world_config::WorldConfigResource;

pub fn player_management_plugin(mut app: &mut App) {
    app.add_systems(Update, handle_new_players);
}

fn handle_new_players(mut commands: Commands, q_new_clients: Query<Entity, Added<ConnectedClient>>, world_config: Res<WorldConfigResource>, planets: Query<(&Transform, &Planet)>) {
    let Some(wc) = &world_config.config else { return; };
    for joined_player in &q_new_clients {
        // find earth
        let (earth_pos, earth_planet) = planets.iter().find(|p| p.1.name == "Earth").expect("earth is missing? (check that the planet is named 'Earth')");
        let angle = rand::random::<f32>() * std::f32::consts::TAU;
        let offset = earth_planet.radius + 150.0;
        let mut new_transform = Transform::from_xyz(angle.cos() * offset, angle.sin() * offset, 0.0);
        new_transform.rotate_z(angle);
        new_transform.translation += earth_pos.translation;


        commands.entity(joined_player)
            .insert(PartBundle {
                part: Part {
                    sprite: "textures/hearty.png".to_string(),
                    width: wc.part.default_width,
                    height: wc.part.default_height,
                    mass: wc.part.default_mass
                },
                transform: new_transform,
                collider: Collider::cuboid(wc.part.default_width / 2.0, wc.part.default_height / 2.0),
                additional_mass_properties: AdditionalMassProperties::MassProperties(MassProperties {
                    local_center_of_mass: Vec2::ZERO,
                    mass: wc.part.default_mass,
                    principal_inertia: 7.5,
                })
            })
            .insert(Replicated)
            .insert(Player {
                client: joined_player,
            });
    }
}