Bevt Event

事件让我们可以在System之间通信,我们可以在一个系统中发送事件,然后在另一个系统中接收事件以触发我们的游戏逻辑。

添加事件

我们先定义我们的事件:

rust 复制代码
#[derive(Event)]
struct PlayerDetected(i32);

事件只需要derive(Event)即可,同时事件也是一个普通的结构体,它可以包含数据,也可以不包含。

在我们声明了事件类型之后,我们需要添加到App中:

rust 复制代码
// other code...
App::new().add_event::<PlayerDetected>()
// other code...

需确保 add_event::<PlayerDetected>() 在注册相关系统之前调用,否则事件无法被识别。

此时,我们就可以在我们的系统中使用事件了。

发送事件

rust 复制代码
fn send_player_detected(mut events: EventWriter<PlayerDetected>) {
    events.send(PlayerDetected(1));
}

发送事件需要定义一个可变的EventWriter,泛型参数填入我们的事件类型,当我们需要触发事件的时候,调用EventWriter.send发送事件。

读取事件

rust 复制代码
fn on_player_detected(mut events: EventReader<PlayerDetected>) {
    events
        .read()
        .for_each(|ev| info!("detected player: {}", ev.0));
}

读取事件稍显特殊,使用EventReader读取事件,调用函数read()会返回一个读取事件的迭代器,如果有事件触发,会进入到for_each中,当然,使用for循环也是一样的。

注册系统

别忘了,把两个系统添加到我们的App中:

rust 复制代码
// other code...
.add_systems(
    Update,
    send_player_detected.run_if(input_just_pressed(KeyCode::Space)),
)
.add_systems(Update, on_player_detected)
// other code...

注意这里我们在触发send_player_detected系统的时候,判定了是否按下空格键。

此时,当我们按下空格键的时候,便会触发PlayerDetected事件。

总结

总体来讲,Bevy 的事件使用起来是比较简单的。事件是将发生的事情应该发生的事情分离的主要方式,通过事件能够让我们的游戏更具可扩展性。

相关推荐
小灰灰搞电子17 小时前
Rust+Slint 实现ModbusRTU从机调试助手源码分享
开发语言·rust·modbusrtu
SmalBox18 小时前
01-04-认知篇-基础-Unity Addressable Assets全面解析
unity3d·游戏开发
Source.Liu19 小时前
Tauri 2.0 + Alpine.js 起步笔记(零构建方案)
rust
小灰灰搞电子19 小时前
Rust+Slint 实现抽屉式侧边栏源码分享
开发语言·rust·侧边栏
码艺-Alimjan20 小时前
Tauri 2.x + Vue 3 桌面应用开发实战:从踩坑到完美落地
前端·javascript·vue.js·rust·typescript·go
右耳朵猫AI20 小时前
Node.js周刊2026W36 | NestJS 12发布、Remix 3 RC、pnpm 12 Rust重写、Node.js 26.8.0
开发语言·rust·node.js
右耳朵猫AI21 小时前
Web前端周刊2026W36 | pnpm 12 Rust 重写、Remix 3 RC、Node.js 26.8.0、htmx 4.0 大版本
前端·rust·node.js
小灰灰搞电子1 天前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
传奇开心果编程1 天前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust