我有一个像这样的节点包:
commands.spawn((
NodeBundle {
style: Style {
position_type: PositionType::Absolute,
height: Val::Px(100.0),
width: Val::Px(100.0),
..Default::default()
},
transform: Transform::from_translation(Vec3::ZERO),
visibility: Visibility::Visible,
background_color: BackgroundColor(Color::BLACK),
..Default::default()
},
Node {
x: 0,
y: 0,
kind: NodeKind::Player,
},
));
我想移动这个节点:
fn move_node(
mut node: Query<(&mut Transform, &mut Node)>,
keyboard_input: Res<ButtonInput<KeyCode>>,
) {
let (mut transform, mut node) = node.single_mut();
if keyboard_input.pressed(KeyCode::KeyD) {
transform.translation.x += 100.0;
} else if keyboard_input.pressed(KeyCode::KeyS) {
transform.translation.y += 100.0;
} else if keyboard_input.pressed(KeyCode::KeyA) {
transform.translation.x -= 100.0;
} else if keyboard_input.pressed(KeyCode::KeyW) {
transform.translation.y -= 100.0;
}
}
我相信 UI 节点的布局会不断重新计算。
Transform
事后保持同步,因此它实际上是只读的。当 UI 呈现时,您的更改将被覆盖。
Style
来实现 - 可能使用 left
和 top
字段,尽管它使用基于 CSS 的布局,可能要复杂得多。
style: Style {
position_type: PositionType::Absolute,
left: Val::Px(100.0),
top: Val::Px(100.0),
height: Val::Px(100.0),
width: Val::Px(100.0),
..Default::default()
}
fn move_node(
mut node: Query<(&mut Style, &mut Node)>,
keyboard_input: Res<ButtonInput<KeyCode>>,
) {
let (mut style, mut node) = node.single_mut();
if keyboard_input.pressed(KeyCode::KeyD) {
if let Val::Px(left) = &mut style.left {
*left += 10.0;
}
} else if keyboard_input.pressed(KeyCode::KeyS) {
if let Val::Px(top) = &mut style.top {
*top += 10.0;
}
} else if keyboard_input.pressed(KeyCode::KeyA) {
if let Val::Px(left) = &mut style.left {
*left -= 10.0;
}
} else if keyboard_input.pressed(KeyCode::KeyW) {
if let Val::Px(top) = &mut style.top {
*top -= 10.0;
}
}
}
注意:我看到这是给你自己的
Node
和 NodeKind::Player
;使用 UI 组件作为游戏的核心可能是个坏主意。有很多用于制作 2D 游戏的示例。