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

我正在尝试为游戏添加子弹射击功能。子弹射击,但每次将子弹添加到场景中时,它都会在 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!



它仍然不起作用,我不知道为什么。


森栏
浏览 107回答 3
3回答

守着星空守着你

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

红糖糍粑

你认为这里发生了什么?bullet.setTranslateX(imgView.getTranslateX()&nbsp;+&nbsp;110); bullet.setTranslateY(imgView.getTranslateY()&nbsp;-&nbsp;57.5);由于这些值永远不会重置(例如设置为 0.0),因此它们每次都会相加。

青春有我

答案是使用 Pane 而不是 VBox。在尝试弥补使用 VBox 之后,通过一些额外的位置编辑来重新调整,我终于让枪在相同的 Y 位置发射每颗子弹。感谢所有提供帮助的人!:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java