bevy自带的画图功能有点弱,得先引入bevy_prototype_lyon, Cargo.toml依赖部分如下:
代码语言:javascript复制[dependencies]
bevy = { version = "0.5.0", features = ["dynamic"] }
bevy_prototype_lyon = "0.3.1"
main.rs完整代码如下,已经加了详细注释,应该不难看懂
代码语言:javascript复制use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin};
use bevy::prelude::*;
use bevy_prototype_lyon::prelude::*;
#[derive(Default)]
struct ExampleShape;
// 速度
#[derive(Default)]
struct Speed(i8);
// x軸移動方向(1右,-1左,0靜止)
#[derive(Default)]
struct XDirection(i8);
// y軸移動方向(1上,-1下,0靜止)
#[derive(Default)]
struct YDirection(i8);
//按键移动
fn move_shape(
input: Res<Input<KeyCode>>,
mut query: Query<&mut Transform, With<ExampleShape>>,
speed: Res<Speed>,
mut x_direct: ResMut<XDirection>,
mut y_direct: ResMut<YDirection>,
) {
for mut transform in query.iter_mut() {
if input.just_pressed(KeyCode::Left) {
x_direct.0 = -1;
}
if input.just_pressed(KeyCode::Right) {
x_direct.0 = 1;
}
if input.just_pressed(KeyCode::Down) {
y_direct.0 = -1;
}
if input.just_pressed(KeyCode::Up) {
y_direct.0 = 1;
}
if input.just_pressed(KeyCode::Space) {
x_direct.0 = 0;
y_direct.0 = 0;
}
transform.translation.x = speed.0 as f32 * x_direct.0 as f32;
transform.translation.y = speed.0 as f32 * y_direct.0 as f32;
}
}
/**
* 初始化
*/
fn setup(mut commands: Commands) {
//畫圓
let shape = shapes::Circle {
radius: 20.,
..shapes::Circle::default()
};
//声明1个2d"对象"
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
commands
.spawn_bundle(GeometryBuilder::build_as(
&shape,
ShapeColors::outlined(Color::TEAL, Color::BLACK),
DrawMode::Outlined {
//画外框
fill_options: FillOptions::default(),
outline_options: StrokeOptions::default().with_line_width(1.0),
},
Transform::default(),
))
.insert(ExampleShape);
}
fn main() {
App::build()
//防锯齿
.insert_resource(Msaa { samples: 8 })
//设置窗口属性
.insert_resource(WindowDescriptor {
title: "make things move".to_string(),
width: 400.,
height: 300.,
resizable: false,
..Default::default()
})
//初始化x轴方向
.insert_resource(XDirection(0))
//初始化y轴方向
.insert_resource(YDirection(0))
//初始化速度
.insert_resource(Speed(1))
//初始化
.add_startup_system(setup.system())
//添加按键控制系统
.add_system(move_shape.system())
//打印帧数等信息
.add_plugin(LogDiagnosticsPlugin::default())
.add_plugin(FrameTimeDiagnosticsPlugin::default())
//加载默认插件
.add_plugins(DefaultPlugins)
//加载画图插件
.add_plugin(ShapePlugin)
.run();
}
运行效果: