Untitled

mail@pastecode.io avatar
unknown
rust
7 months ago
9.2 kB
7
Indexable
Never
// World

use bevy::{
    math::Vec3,
    prelude::{Component, Resource},
};

pub const FIELD_1_FLOWERS_ROW: i32 = 20;
pub const FIELD_1_FLOWERS_COLUMN: i32 = 13;

#[derive(Component)]
pub struct Ground {}

#[derive(Component, Default, Clone, Debug)]
pub struct FlowerField {
    pub which_field: String,
    pub positions: Vec<Vec3>,
}

#[derive(Component)]
pub struct Flower {
    pub flower_type: Type,
    pub stage: u8,
    pub how_many: u8,
}

pub enum Type {
    White,
    Blue,
    Red,
}

#[derive(Resource, Default, Debug)]
pub struct FlowerFields {
    pub flower_fields: Vec<FlowerField>,

// Systems

pub fn setup_world(
    mut commands: Commands,
    _materials: ResMut<Assets<StandardMaterial>>,
    mut ambient_light: ResMut<AmbientLight>,
    asset_server: Res<AssetServer>,
) {
    let meshes: Vec<Handle<Scene>> = vec![
        asset_server.load("meshes/world.glb#Scene0"),
        asset_server.load("meshes/spawn.glb#Scene0"),
        asset_server.load("meshes/field_1.glb#Scene0"),
    ];
    let flower_meshes: Vec<Handle<Scene>> = vec![
        asset_server.load("meshes/flower_white.glb#Scene0"),
        asset_server.load("meshes/flower_blue.glb#Scene0"),
        asset_server.load("meshes/flower_red.glb#Scene0"),
    ];

    let ground = (
        SceneBundle {
            scene: meshes[0].clone(),
            ..Default::default()
        },
        Collider::cuboid(200.0, 0.01, 200.0),
        RigidBody::Fixed,
        Ground {},
    );

    let spawn = (
        SceneBundle {
            scene: meshes[1].clone(),
            ..Default::default()
        },
        Collider::cuboid(2.0, 0.2, 2.0),
        RigidBody::Fixed,
        Ground {},
    );

    let field_1 = commands
        .spawn((
            SceneBundle {
                scene: meshes[2].clone(),
                transform: Transform::from_xyz(0.0, 0.01, 15.0),
                ..Default::default()
            },
            Collider::cuboid(10.0, 0.1, 7.0),
            RigidBody::Fixed,
            Ground {},
            FlowerField {
                which_field: "field_1".to_string(),
                positions: Vec::new(),
            },
        ))
        .with_children(|p| {
            for test in 0..FIELD_1_FLOWERS_ROW {
                for notest in 0..FIELD_1_FLOWERS_COLUMN {
                    let mut rng = rand::thread_rng();
                    let random_number = rng.gen_range(0..=99);

                    let mut x_value: f32 = test as f32;
                    let mut y_value: f32 = notest as f32;

                    x_value -= 10.0;
                    y_value -= 6.0;

                    // Check the probability ranges and print accordingly
                    if random_number < 70 {
                        p.spawn((
                            SceneBundle {
                                scene: flower_meshes[0].clone(),
                                transform: Transform::from_xyz(x_value, 0.0, y_value),
                                ..Default::default()
                            },
                            Flower {
                                flower_type: Type::White,
                                stage: 3,
                                how_many: 1,
                            },
                        ));
                    } else if random_number < 85 {
                        p.spawn((
                            SceneBundle {
                                scene: flower_meshes[1].clone(),
                                transform: Transform::from_xyz(x_value, 0.0, y_value),
                                ..Default::default()
                            },
                            Flower {
                                flower_type: Type::Blue,
                                stage: 3,
                                how_many: 1,
                            },
                        ));
                    } else {
                        p.spawn((
                            SceneBundle {
                                scene: flower_meshes[2].clone(),
                                transform: Transform::from_xyz(x_value, 0.0, y_value),
                                ..Default::default()
                            },
                            Flower {
                                flower_type: Type::Red,
                                stage: 3,
                                how_many: 1,
                            },
                        ));
                    }
                }
            }
        })
        .id();

    let ground_id = commands.spawn(ground).id();
    let spawn_id = commands.spawn(spawn).id();

    println!(
        "ground Id: {:?}, spawn Id: {:?}, field_1 Id: {:?}",
        ground_id, spawn_id, field_1
    );

    ambient_light.brightness = 0.8;
}

pub fn spawn_positions(
    mut flowerfield: Query<&mut FlowerField>,
    mut flowerfieldsres: ResMut<FlowerFields>,
) {
    for mut flowerfields in flowerfield.iter_mut() {
        match flowerfields.which_field.as_str() {
            "field_1" => {
                for test in 0..FIELD_1_FLOWERS_ROW {
                    for notest in 0..FIELD_1_FLOWERS_COLUMN {
                        let mut x_value: f32 = test as f32;
                        let mut y_value: f32 = notest as f32;

                        x_value -= 10.0;
                        y_value -= 6.0;

                        flowerfields.positions.push(Vec3 {
                            x: (x_value),
                            y: (0.0),
                            z: (y_value),
                        });
                    }
                }
            }
            _ => println!("No Field!"),
        };
        flowerfieldsres.flower_fields.push(flowerfields.clone());
    }
}


// Player

use bevy::prelude::*;

#[derive(Component)]
pub struct Player {}

#[derive(Component)]
pub struct Speed(pub f32);

#[derive(Resource, Default)]
pub struct OnGround {
    pub is_grounded: bool,
}

#[derive(Resource, Default)]
pub struct SwingTimer {
    pub timer: Timer,
}

#[derive(Resource)]
pub struct PlayerAnimations(pub Vec<Handle<AnimationClip>>);

#[derive(Component, Default)]
pub struct Collector {
    pub name: String,
    pub collect_amount: u32,
    pub mesh_handle: Handle<Scene>,

    // Swing
    pub can_swing: bool,
}

#[derive(Event)]
pub struct Collect {}

#[derive(Resource, Default)]
pub struct InField {
    pub is_in_field: bool,
    pub which_field: String,
}

#[derive(Component)]
pub struct SwingFromWhere {}

//Systems

pub fn is_in_field(
    player_q: Query<Entity, With<Player>>,
    field_q: Query<(Entity, &FlowerField), With<FlowerField>>,
    mut contact_force_events: EventReader<ContactForceEvent>,
    mut in_field: ResMut<InField>,
) {
    let player = player_q.single();

    for contact_force_event in contact_force_events.read() {
        let entity_1 = contact_force_event.collider1;
        let entity_2 = contact_force_event.collider2;

        for (entity, field) in field_q.iter() {
            if (entity_1 == player) && (entity_2 == entity) {
                in_field.is_in_field = true;

                match field.which_field.as_str() {
                    "field_1" => in_field.which_field = field.which_field.clone(),
                    _ => println!("Wrong FlowerField Name!"),
                };
            } else {
                in_field.is_in_field = false;
            }
        }
    }
}

pub fn collector_swinging_system(
    time: Res<Time>,
    input: Res<Input<MouseButton>>,
    player_animations: Res<PlayerAnimations>,
    mut query: Query<(&mut Collector, &mut Transform)>,
    mut player_query: Query<&mut AnimationPlayer>,
    mut swing_timer: ResMut<SwingTimer>,
    mut event_writer: EventWriter<Collect>,
) {
    for (mut collector, _transform) in query.iter_mut() {
        if input.just_pressed(MouseButton::Left) && collector.can_swing {
            for mut player in &mut player_query {
                player.play(player_animations.0[0].clone_weak());
                player.replay();
            }

            event_writer.send(Collect {});

            collector.can_swing = false;
            swing_timer.timer.reset();
        }

        swing_timer.timer.tick(time.delta());
        collector.can_swing = swing_timer.timer.finished();
    }
}

pub fn collect_flowers(
    mut event_reader: EventReader<Collect>,
    in_field: Res<InField>,
    player_q: Query<&Transform, With<SwingFromWhere>>,
    flowerfields: Res<FlowerFields>,
) {
    let mut which_field: usize = 0;

    for _event in event_reader.read() {
        if in_field.is_in_field {
            match in_field.which_field.as_str() {
                "field_1" => which_field = 0,
                _ => println!("Something went wronglol!"),
            };

            //let positions: i32 = flowerfields.flower_fields[which_field].positions.len() as i32;
            let player_position = player_q.single().translation;

            for &position in &flowerfields.flower_fields[which_field].positions {
                let distance = player_position.distance(position); // Calculate distance

                if distance < 3.0 {
                    println!("Harvestable");
                }
            }
        }
    }
}
Leave a Comment