use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, button_interaction)
.run();
}
#[derive(Component)]
struct ClickText; // 标记需要更新的文本
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
println!("{}","程序成功载入");
// 2D 相机
commands.spawn(Camera2dBundle::default());
// 根节点(全屏居中)
commands
.spawn(NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
..default()
})
.with_children(|parent| {
// 按钮
parent.spawn(ButtonBundle {
style: Style {
width: Val::Px(150.0),
height: Val::Px(65.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
background_color: Color::rgb(0.25, 0.25, 0.25).into(),
..default()
})
.with_children(|btn| {
// 按钮文本
btn.spawn(TextBundle::from_section(
"点击我!",
TextStyle {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 30.0,
color: Color::WHITE,
},
));
});
// 显示点击次数的文本
parent.spawn((
TextBundle::from_section(
"Clicks: 0",
TextStyle {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 40.0,
color: Color::WHITE,
},
)
.with_style(Style {
margin: UiRect::top(Val::Px(50.0)),
..default()
}),
ClickText, // 标记组件
));
});
}
// 按钮交互系统
fn button_interaction(
mut interaction_query: Query<&Interaction, (Changed<Interaction>, With<Button>)>,
mut text_query: Query<&mut Text, With<ClickText>>,
mut clicks: Local<u32>,
) {
for interaction in &mut interaction_query {
if *interaction == Interaction::Pressed {
*clicks += 1;
for mut text in &mut text_query {
text.sections[0].value = format!("Clicks: {}", *clicks);
}
}
}
}