用途
本技能用于将触屏优先的 Bevy 移动端游戏适配到桌面端。当游戏新增窗口、鼠标和键盘输入时加载。窗口设置本身由 bevy-platform-desktop 负责。
主要能力
技能围绕 Bevy ECS 展开,涉及以下类型与模块:
- 窗口:Window、WindowMode、PrimaryWindow。
- 输入:键盘、鼠标、手柄功能,由 bevy-input-handling 使用。
- 指针:主窗口上的 CursorOptions,抓取模式为 CursorGrabMode::None、Confined 或 Locked。
桌面端常见选择:
- 屏幕按钮:通过 bevy-input-handling 使用键盘和鼠标,写入相同的意图组件。
- 更宽布局:在主 Window 上设置更宽的 WindowResolution。
- 指针锁定:CursorOptions.grab_mode = CursorGrabMode::Locked,visible = false。
使用方式
技能给出多个代码示例,包括:
- 打开 1920x1080 窗口视图,并在瞄准时锁定指针。
- 用 WASD 替代屏幕摇杆,游戏系统读取 MoveIntent 而非键码。
- 用 F11 切换全屏。
- 使用 AccumulatedMouseMotion 实现捕获式视角。
示例依赖:
[package]
name = "desktop_port"
version = "0.1.0"
edition = "2021"
[dependencies]
bevy = "0.20"
窗口设置示例:
use bevy::window::{
CursorGrabMode, CursorOptions, MonitorSelection, PresentMode, PrimaryWindow, WindowMode,
WindowResolution,
};
fn desktop_window(mut windows: Query<&mut Window, With<PrimaryWindow>>) {
for mut window in &mut windows {
window.mode = WindowMode::Windowed;
window.resolution = WindowResolution::new(1920, 1080);
window.title = "Desktop".to_string();
window.present_mode = PresentMode::AutoVsync;
}
}
WASD 移动示例:
#[derive(Component, Default)]
struct MoveIntent(Vec2);
fn read_wasd(keys: Res<ButtonInput<KeyCode>>, mut intents: Query<&mut MoveIntent>) {
let mut dir = Vec2::ZERO;
if keys.pressed(KeyCode::KeyA) {
dir.x -= 1.0;
}
if keys.pressed(KeyCode::KeyD) {
dir.x += 1.0;
}
if keys.pressed(KeyCode::KeyW) {
dir.y += 1.0;
}
if keys.pressed(KeyCode::KeyS) {
dir.y -= 1.0;
}
for mut intent in &mut intents {
intent.0 = dir;
}
}
适用场景
- 触屏游戏需要新增窗口、鼠标和键盘支持。
- 需要将屏幕按钮替换为键盘鼠标输入,同时保持游戏逻辑设备无关。
- 需要设置窗口模式、分辨率、呈现模式或指针抓取。
- 需要实现全屏切换或捕获式鼠标视角。
限制与规则
技能明确列出以下禁止事项:
- 不要在文档 URL 中固定 /0.20.0/,链接保持最新,0.20 目标只在正文中说明一次。
- 不要从两个无序系统可变查询同一组件,因为调度会并行运行系统,除非用 .chain() 排序。
- 不要在此发明物理、导航、网络或 XR crate,本技能只命名有文档的 Bevy crate 和模块。
- 不要有绕过 MoveIntent 的第二条输入路径,键盘、鼠标和触屏必须写入同一组件。
- 不要使用虚构 API 或未命名的第三方 crate 作为求解器。
ECS 所有权规则:
- 单个实体上的数据由 Component 拥有,一个系统通过 Query 修改,运行在 Update 或 FixedMain。
- 整个应用的一个值由 Resource 拥有,一个系统修改,Startup 插入后由读取它的调度使用。
- 生成由 Commands 负责,生成系统执行,Startup 用于初始世界,后续调度用于运行时生成。
- 不能竞态的顺序用 .chain() 保证,仅限被链的系统,同一调度内。
- 插件边界由 Plugin 负责,build 注册系统和资源,在应用运行前。
借用规则:两个系统若都可变查询同一组件,必须用 .chain() 排序,或拆分使只有一个写入。无关系统保持并行。
相关技能
前置:bevy-master(枢纽与调度)、bevy-ecs-composition(组件与系统)、bevy-platform-desktop(窗口)、bevy-input-handling(键盘、鼠标、手柄)。
互补:bevy-adapt-desktop-to-mobile(反向适配)。
下游消费者:暂无。
主技能:bevy-master(Bevy 路由器)。
参考
官方文档包括:Assets(官方资源目录,未选择第三方 crate)、Examples(最新分支的示例树)、Window examples(WindowMode、呈现模式、指针抓取)、ECS(Component、系统、Query、Startup、Update、.chain())、Plugins(Plugin、DefaultPlugins、MinimalPlugins、add_plugins)。
库固定版本:bevy-master 保持 0.20.0,永久链接保持无版本。