Skip to content

低功耗模式

默认情况下 Bevy 尽可能快地渲染(UpdateMode::Continuous)。对于桌面应用或工具,这浪费了大量 CPU/GPU 资源。WinitSettings 控制渲染频率。

rust
use bevy::prelude::*;
use bevy::winit::WinitSettings;

fn main() {
    App::new()
        .insert_resource(WinitSettings::desktop_app())
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, log_frame)
        .run();
}

fn setup() {
    info!("低功耗模式——desktop_app(): 无输入时不渲染,省电");
}

fn log_frame(mut frame: Local<u32>, time: Res<Time>) {
    *frame += 1;
    if *frame % 300 == 0 {
        info!(
            "frame {}, elapsed {:.1}s",
            *frame,
            time.elapsed().as_secs_f32()
        );
    }
}

Listing 35-4:低功耗模式——desktop_app()

WinitSettings 预设

预设焦点模式失焦模式适用场景
game()Continuousreactive_low_power(1/60s)游戏(默认)
desktop_app()reactive(5s)reactive_low_power(60s)桌面应用
mobile()reactive(1/60s)reactive_low_power(1s)移动端
continuous()ContinuousContinuous始终满帧

UpdateMode

变体行为
Continuous尽可能快地渲染
Reactive { wait, ... }有事件或超过 wait 时间才渲染

reactive_low_power(wait)Reactive 的特化:忽略设备级事件(如鼠标在窗口外移动),只响应窗口级交互。

RequestRedraw

即使在 Reactive 模式下,也可以主动请求一帧渲染:

rust
redraw_request_writer.write(RequestRedraw);

这在 UI 动画需要持续播放但不想用 Continuous 模式时很有用。

实际效果

desktop_app() 模式下:

  • 无交互时 CPU 占用接近 0
  • 窗口移动、鼠标点击等交互时立即响应
  • 超过 5 秒无交互会暂停渲染,节省电量
  • 失焦后 60 秒才暂停,避免频繁切换