The Bevy Book - 2.5 資源Resources
阿新 • • 發佈:2022-05-29
資源
實體和元件非常適合表示複雜的、可查詢的資料組。但大多數應用程式還需要某種"globally unique"的資料。在 Bevy ECS 中,我們使用資源來表示全域性唯一資料。
以下是一些可以寫成Resources的資料示例:
- 已用時間 Elapsed Time
- 資源集合(聲音、紋理、網格) Asset Collections
- 渲染器 Renderers
使用Resources跟蹤時間
讓我們解決應用程式的“hello spam”問題,每兩秒鐘只打印一次“hello”。我們將使用Time
資源來執行此操作,該資源通過add_plugins(DefaultPlugins)
自動新增到我們的應用程式中。
為簡單起見,請從應用程式中刪除hello_world
系統。這樣,我們只需要調整greet_people
系統。
訪問資源的方式與訪問元件的方式大致相同。您可以像這樣訪問系統中的Time
資源:
fn greet_people(time: Res<Time>, query: Query<&Name, With<Person>>) {
for name in query.iter() {
println!("hello {}!", name.0);
}
}
Res
和ResMut
指標分別提供對資源的讀取和寫入訪問許可權。
delta_seconds
Time
欄位為我們提供了自上次更新以來經過的時間。但是,為了每兩秒執行一次我們的系統,我們必須跟蹤經過一系列更新的時間量。為了簡化此操作,Bevy 提供了該Timer
型別。讓我們為系統建立一個新資源,用上Timer
:
struct GreetTimer(Timer); fn greet_people( time: Res<Time>, mut timer: ResMut<GreetTimer>, query: Query<&Name, With<Person>>) { // update our timer with the time elapsed since the last update // if that caused the timer to finish, we say hello to everyone if timer.0.tick(time.delta()).just_finished() { for name in query.iter() { println!("hello {}!", name.0); } } }
現在剩下的就是將GreetTimer
資源新增到我們的HelloPlugin
:
impl Plugin for HelloPlugin {
fn build(&self, app: &mut App) {
// the reason we call from_seconds with the true flag is to make the timer repeat itself
app.insert_resource(GreetTimer(Timer::from_seconds(2.0, true)))
.add_startup_system(add_people)
.add_system(greet_people);
}
}
現在cargo run
應用程式。它現在應該以合理的速度向人們打招呼。