~starkingdoms/starkingdoms

ref: ad2517ff63342f5d076ebc7b72f83a4b68b9b19f starkingdoms/crates/unified/src/client/crafting/ui.rs -rw-r--r-- 2.2 KiB
ad2517ffghostly_zsh feat: crafting ui start a month 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use bevy::{input_focus::{AutoFocus, InputFocus}, ui::RelativeCursorPosition};

use crate::{attachment::PartInShip, client::colors, ecs::{CanCraft, CraftingUi, MainCamera, Me}, prelude::*};

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

pub fn open_crafting_ui(
    ev: On<Pointer<Press>>,
    crafting_parts: Query<(Entity, &Transform), (With<PartInShip>, With<CanCraft>)>,
    hearty: Query<(Entity, &Transform), (With<Me>, With<CanCraft>)>,
    camera: Single<(Entity, &Camera, &GlobalTransform), (With<MainCamera>, Without<PartInShip>)>,
    commands: Commands,
) {
    if matches!(ev.button, PointerButton::Secondary) {
        let (entity, transform) = if let Ok(part) = crafting_parts.get(ev.entity) {
            part
        } else if let Ok(part) = hearty.get(ev.entity) {
            part
        } else {
            return
        };
        // we have our crafting entity!
        // now make the ui
        setup_ui(transform, commands, camera);
    }
}

fn setup_ui(
    parent_transform: &Transform,
    mut commands: Commands,
    camera: Single<(Entity, &Camera, &GlobalTransform), (With<MainCamera>, Without<PartInShip>)>,
) {
    let parent_pos = camera.1.world_to_viewport(camera.2, parent_transform.translation).unwrap();
    let entity = commands.spawn((
        UiTargetCamera(camera.0),
        Node {
            position_type: PositionType::Absolute,
            left: Val::Px(parent_pos.x),
            top: Val::Px(parent_pos.y),
            width: Val::Px(100.0),
            height: Val::Px(100.0),
            ..default()
        },
        AutoFocus,
        CraftingUi,
        BackgroundColor(colors::MANTLE),
        RelativeCursorPosition::default(),
    ));
}

pub fn close_ui(
    buttons: Res<ButtonInput<MouseButton>>,
    crafting_ui: Query<(Entity, &RelativeCursorPosition), With<CraftingUi>>,
    mut commands: Commands,
) {
    if crafting_ui.is_empty() { return }
    if !buttons.any_just_released([MouseButton::Left, MouseButton::Right]) { return }

    for (_, cursor_pos) in &crafting_ui {
        if cursor_pos.cursor_over {
            return;
        }
    }

    for (entity, _) in &crafting_ui {
        commands.entity(entity).despawn();
    }
}