为了账号安全,请及时绑定邮箱和手机立即绑定

每次添加到布局时,JavaFX 图像都会落在 Y 轴上

每次添加到布局时,JavaFX 图像都会落在 Y 轴上

森栏 2023-06-08 20:44:37
我正在尝试为游戏添加子弹射击功能。子弹射击,但每次将子弹添加到场景中时,它都会在 Y 轴上减小。我的目标是每次添加项目符号时都将其添加到布局中 X 轴和 Y 轴上的相同位置。我试图通过使用进行检查,if (!(layout.getChildren().contains(bullet))) {但它仍然没有用。public class AnimationTest {static Stage primaryStage = new Stage();static VBox layout = new VBox(10);static Image image = new Image("/run-gun.png");static Image bulletI = new Image("/bullet.png");static ImageView bullet;public static void main(String[] args){}public static void start() throws Exception {imgView = new ImageView(image);bullet = new ImageView(bulletI);Scene scene = new Scene(layout);    layout.getChildren().add(imgView);    primaryStage.setScene(scene);    primaryStage.show();scene.setOnKeyPressed(e -> {getKey(e);});}public static void getKey(KeyEvent e){bullet = new ImageView(bulletI);if (e.getCode() == KeyCode.SPACE) {        if (layout.getChildren().contains(bullet)) {    } else {        layout.getChildren().add(bullet);        bullet.setTranslateX(imgView.getTranslateX() + 110);        bullet.setTranslateY(imgView.getTranslateY() - 57.5);        posY = (int) bullet.getTranslateY();        bullet.setTranslateY(posY);        // move bullet        TranslateTransition tt = new TranslateTransition(Duration.millis(750), bullet);        tt.setByX(1920);        tt.setCycleCount(1);        tt.setAutoReverse(false);        tt.setOnFinished(new EventHandler<ActionEvent>() {            public void handle(ActionEvent event) {                 try {                     removeBullet();                    } catch (Exception e) {                        e.printStackTrace();                    }            }            });        tt.play();    }    } else {    }}}I want the bullet image to ALWAYS be added to the layout in the same X and Y positions. Thanks!它仍然不起作用,我不知道为什么。
查看完整描述

3 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

对于这种绝对定位,使用任何类型的布局窗格(如 HBox)都不是一个好主意,因为这总是会干扰您的定位。最好在这里只使用一个不做任何布局的窗格。



查看完整回答
反对 回复 2023-06-08
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

你认为这里发生了什么?

bullet.setTranslateX(imgView.getTranslateX() + 110);
bullet.setTranslateY(imgView.getTranslateY() - 57.5);

由于这些值永远不会重置(例如设置为 0.0),因此它们每次都会相加。


查看完整回答
反对 回复 2023-06-08
?
青春有我

TA贡献1784条经验 获得超8个赞

答案是使用 Pane 而不是 VBox。在尝试弥补使用 VBox 之后,通过一些额外的位置编辑来重新调整,我终于让枪在相同的 Y 位置发射每颗子弹。感谢所有提供帮助的人!:)



查看完整回答
反对 回复 2023-06-08
  • 3 回答
  • 0 关注
  • 106 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信