aboutsummaryrefslogtreecommitdiff
path: root/azalea/examples/nearest_entity.rs
blob: 8774829e1f321d82db25cfcbc05fe2d6024d40c3 (plain)
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
71
use azalea::{Bot, ClientBuilder, LookAtEvent, nearest_entity::EntityFinder};
use azalea_client::Account;
use azalea_core::tick::GameTick;
use azalea_entity::{
    EyeHeight, LocalEntity, Position,
    metadata::{ItemItem, Player},
};
use bevy_app::Plugin;
use bevy_ecs::{
    prelude::{Entity, EventWriter},
    query::With,
    system::Query,
};

#[tokio::main(flavor = "current_thread")]
async fn main() {
    let account = Account::offline("bot");

    ClientBuilder::new()
        .add_plugins(LookAtStuffPlugin)
        .start(account, "localhost")
        .await
        .unwrap();
}

pub struct LookAtStuffPlugin;
impl Plugin for LookAtStuffPlugin {
    fn build(&self, app: &mut bevy_app::App) {
        app.add_systems(GameTick, (look_at_everything, log_nearby_item_drops));
    }
}

fn look_at_everything(
    bots: Query<Entity, (With<LocalEntity>, With<Player>)>,
    entities: EntityFinder,
    entity_positions: Query<(&Position, Option<&EyeHeight>)>,
    mut look_at_event: EventWriter<LookAtEvent>,
) {
    for bot_id in bots.iter() {
        let Some(entity) = entities.nearest_to_entity(bot_id, 16.0) else {
            continue;
        };

        let (position, eye_height) = entity_positions.get(entity).unwrap();

        let mut look_target = **position;
        if let Some(eye_height) = eye_height {
            look_target.y += **eye_height as f64;
        }

        look_at_event.write(LookAtEvent {
            entity: bot_id,
            position: look_target,
        });
    }
}

fn log_nearby_item_drops(
    bots: Query<Entity, With<Bot>>,
    entities: EntityFinder<With<ItemItem>>,
    item_drops: Query<&ItemItem>,
) {
    for bot_id in bots.iter() {
        for (entity, distance) in entities.nearby_entities_to_entity(bot_id, 8.0) {
            let item_drop = item_drops.get(entity).unwrap();
            let kind = item_drop.kind();

            println!("Bot {bot_id:?} can see an {kind:?} {distance:.1} meters away.");
        }
    }
}