gpt4 book ai didi

rust - 没有多个按钮系统的多个按钮?

转载 作者:行者123 更新时间:2023-12-03 11:47:36 24 4
gpt4 key购买 nike

我对 rust 刚起步,对新手却比较陌生。我意识到这是早期,并且非常喜欢bevy,但是坦率地说,我缺少示例和文档。
我以/examples/ui/button.rs为起点。我想添加一堆按钮,而不只是一个。
我正在寻找一种方法来区分单击了什么按钮。
我意识到我可以为每个按钮添加一个系统,但这在任何语言中都不是正确的方法。
因此,我开始添加标记(如bevy-cheatsheet建议的那样)。

commands
.spawn(ButtonComponents { /* cut for brevity */ })
.with_children(|parent| {
parent
.spawn(TextComponents { /* cut for brevity */ })
.with(Marker1);
});
但是,我该如何检查产生按钮的标记呢?
fn button_system(
button_materials: Res<ButtonMaterials>,
mut interaction_query: Query<(
&Button,
Mutated<Interaction>,
&mut Handle<ColorMaterial>,
&Children,
)>,
text_query: Query<&mut Text>,
) {
for (_button, interaction, mut material, children) in &mut interaction_query.iter() {
let mut text = text_query.get_mut::<Text>(children[0]).unwrap();
match *interaction {
Interaction::Clicked => {

// This obviously doesn't work, just to illustrate what I'm looking for.
match text.spawned_with {
Marker1 => doSomething(),
Marker2 => doBarrelRoll(),
_ => unreachable!()
}

}
Interaction::Hovered => {
text.value = "Hover".to_string();
*material = button_materials.hovered.clone();
}
Interaction::None => {
text.value = "Button".to_string();
*material = button_materials.normal.clone();
}
}
}
}
任何提示都欢迎,谢谢!
编辑:现在我很困惑,因为这实际上适用于按钮1(但会使button2崩溃):
Interaction::Clicked => {
let marker = text_query.get::<_>(children[0]).unwrap();
match *marker {
Marker1 => println!("marker 1"),
_ => unreachable!(),
}
}
但这甚至没有建立:
    let marker = text_query.get::<_>(children[0]).unwrap();
match *marker {
Marker1 => println!("marker 1"),
Marker2 => println!("marker 2"),
_ => unreachable!(),
}
这是错误:
   |                     expected struct `Marker1`, found struct `Marker2`
| `Marker2` is interpreted as a unit struct, not a new binding
| help: introduce a new binding instead: `other_marker2`

最佳答案

好的,我找到了答案,但是如果您有更优雅的东西,我很乐于学习并做出正确的答案!

Interaction::Clicked => {
if let Ok(_) = text_query.get::<Marker1>(children[0]) {
println!("marker 1")
}
if let Ok(_) = text_query.get::<Marker2>(children[0]) {
println!("marker 2")
}
if let Ok(_) = text_query.get::<Marker3>(children[0]) {
doBarrelRoll()
}
...
}

丹尼尔·库尔曼斯(daniel kullmans)发表评论后,我得到的是这样的内容:
#[derive(PartialEq)]    // needed for comparison
pub enum Buttons {
MyFirstButton,
MySecondButton,
}
struct MyButton {
target: Buttons,
}
和...
commands
.spawn(ButtonComponents { /* cut for brevity */ })
.with_children(|parent| {
parent
.spawn(TextComponents { /* cut for brevity */ })
.with(MyButton { target: Buttons });
});
和...
Interaction::Clicked => {
if let Ok(btn) = text_query.get_mut::<MyButton>(children[0]) {
match btn.target {
Buttons::MyFirstButton => {
...
},
Buttons::MySecondButton => {
...
},
_ => unreachable!(),
}
}
}

关于rust - 没有多个按钮系统的多个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64420915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com