-3

So I'm making a game where the enemies follow the player and the player kills them. How do I make the enemies' ImageViews follow the player.

I have tried some if sentences but I actually have no idea. I also searched everywhere but I only find other people doing it with Swing and I get really confused with a lot of things. I use Javafx btw.

public class Main extends Application{

    private static final int HEIGHT = 720;
    private static final int WIDTH = 1280;
    Scene scene;
    BorderPane root, htpLayout;
    VBox buttons, paragraphs, images;
    Button startButton, htpButton, htpReturnButton, leaderboardButton, exitButton;
    Text gameName, paragraph1, paragraph2, paragraph3;
    Pane gameLayout;
    ImageView background;
    Game game = new Game();
    Player player = new Player();

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage window) throws Exception {

        root = new BorderPane();
        background = new ImageView("stick mob slayer background.png");
        background.fitWidthProperty().bind(window.widthProperty());
        background.fitHeightProperty().bind(window.heightProperty());
        root.getChildren().add(background);
        htpLayout = new BorderPane();

        buttons = new VBox(15);

        scene = new Scene(root, WIDTH, HEIGHT);
        scene.getStylesheets().add("mobslayer/style.css");

        gameName = new Text("Mob Slayer Unlimited");
        gameName.setFont(Font.font("Complex", 50));
        gameName.setFill(Color.WHITE);

        root.setAlignment(gameName, Pos.CENTER_LEFT);
        root.setTop(gameName);

        startButton = new Button("Start Game");
        startButton.setOnAction(e -> window.setScene(game.getScene()));

        htpButton = new Button("How To Play");
        htpButton.setOnAction(e -> scene.setRoot(htpLayout));

        leaderboardButton = new Button("Leaderboard");

        exitButton = new Button("Exit");
        exitButton.setOnAction(e -> Platform.exit());

        buttons.getChildren().addAll(startButton, htpButton, leaderboardButton, exitButton);
        root.setCenter(buttons);
        buttons.setAlignment(Pos.CENTER);

        paragraphs = new VBox(30);
        paragraph1 = new Text("Objektive\nNär spelet börjar kommer huvudkaraktären möta monster.\n"
                + "Ju längre in i spelet du kommer, ju fler och svårare monster dyker upp.\n"
                + "Ditt mål är att överleva så länge som möjligt.");
        paragraph1.setFont(Font.font("Dubai", 13));
        paragraph1.setFill(Color.BLACK);

        paragraph2 = new Text("Movement\nAlla monster dras imot dig, så du måste akta dig.\n"
                + "Detta gör du med hjälp av piltangenterna.");
        paragraph2.setFont(Font.font("Dubai", 13));
        paragraph2.setFill(Color.BLACK);

        paragraph3 = new Text("Special Effects\nDu kan också attackera tillbaka med en lätt attack(c)\n"
                + "eller med en specialattack(space) som dödar alla monster på skärmen.\n"
                + "Du kan dasha(x) för att röra dig snabbare åt ett håll.");
        paragraph3.setFont(Font.font("Dubai", 13));
        paragraph3.setFill(Color.BLACK);

        paragraphs.getChildren().addAll(paragraph1, paragraph2, paragraph3);

        htpReturnButton = new Button("Return");
        htpReturnButton.setOnAction(e->scene.setRoot(root));
        htpLayout.setBottom(htpReturnButton);
        htpLayout.setAlignment(htpReturnButton,Pos.TOP_CENTER);

        images = new VBox(30);
        //      Image image1 = new Image(new FileInputStream("resources\\cod zombies.jpg"));
        //      final ImageView image11 = new ImageView(image1);
        //      image11.setFitHeight(100);
        //      image11.setFitWidth(100);
        //      image11.setPreserveRatio(true);
        //      
        //      Image image2 = new Image(new FileInputStream("resources\\arrowkeys.png")) ;
        //      final ImageView image22 = new ImageView(image2);
        //      image22.setFitHeight(100);
        //      image22.setFitWidth(100);
        //      image22.setPreserveRatio(true);
        //      
        //      Image image3 = new Image(new FileInputStream("resources\\keys.png")) ;
        //      final ImageView image33 = new ImageView(image3);
        //      image33.setFitHeight(100);
        //      image33.setFitWidth(100);
        //      image33.setPreserveRatio(true);
        //      
        //      images.getChildren().addAll(image11, image22, image33);
        //      
        paragraphs.setAlignment(Pos.TOP_LEFT);
        htpLayout.setLeft(paragraphs);
        htpLayout.setRight(images);

        window.setTitle("Mob Slayer Unlimited");
        window.setScene(scene);
        window.setResizable(false);
        window.show();


    }
}
public class Game {

    private static final int HEIGHT = 720;
    private static final int WIDTH = 1280;
    private Scene scene;
    Pane root;
    Text health, stamina, wave, kills;
    int waveCounter = 1, killCounter = 0;
    Button restartButton, pauseButton;
    Line limitUp;
    Player player = new Player();
    Enemies enemy = new Enemies();

    public Game() {

        health = new Text(50, 30, "HP: " + player.getHealth());
        health.setFont(Font.font("BankGothic Lt BT", 30));
        health.setFill(Color.WHITE);

        stamina = new Text(50, 80, "STAMINA: " + player.getStamina());
        stamina.setFont(Font.font("BankGothic Lt BT", 30));
        stamina.setFill(Color.WHITE);

        wave = new Text(1050, 30, "WAVE: " + waveCounter);
        wave.setFont(Font.font("BankGothic Lt BT", 30));
        wave.setFill(Color.WHITE);

        kills = new Text(1050, 80, "KILLS: " + killCounter);
        kills.setFont(Font.font("BankGothic Lt BT", 30));
        kills.setFill(Color.WHITE);

        restartButton = new Button("RESTART");
        restartButton.setFont(Font.font("BankGothic Lt BT", 30));
        restartButton.setOnAction(e -> restart());
        restartButton.setLayoutX(350);
        restartButton.setLayoutY(20);

        pauseButton = new Button("PAUSE");
        pauseButton.setFont(Font.font("BankGothic Lt BT", 30));
        pauseButton.setOnAction(e -> restart());
        pauseButton.setLayoutX(650);
        pauseButton.setLayoutY(20);

        limitUp = new Line(0, 100, 1280, 100);
        limitUp.setStroke(Color.WHITE);

        root = new Pane(player.getSlayer(), limitUp, player.getSlayerHitbox(), health, stamina, wave, kills, restartButton, pauseButton, enemy.getEnemy());
        root.setStyle("-fx-background-color: black");

        enemy.enemyMovement();

        movePlayerTo(WIDTH / 2, HEIGHT / 2);

        scene = new Scene(root, WIDTH, HEIGHT);

        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                switch (event.getCode()) {
                case W:    player.goUp = true; break;
                case S:  player.goDown = true; break;
                case A:  player.goLeft  = true; break;
                case D: player.goRight  = true; break;
                case K: player.running = true; break;
                }
            }
        });

        scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                switch (event.getCode()) {
                case W:    player.goUp = false; break;
                case S:  player.goDown = false; break;
                case A:  player.goLeft  = false; break;
                case D: player.goRight  = false; break;
                case K: player.running = false; break;
                }
            }
        });

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                int dx = 0, dy = 0;

                if (player.goUp) dy -= 2;
                if (player.goDown) dy += 2;
                if (player.goRight)  dx += 2;
                if (player.goLeft)  dx -= 2;
                if (player.running) { dx *= 2; dy *= 2; }
                enemy.enemyMovement();

                movePlayerBy(dx, dy);
            }
        };

        timer.start();


    }

    public Scene getScene() {
        return scene;
    }

        // I took this methods for movement from Github

    public void movePlayerBy(int dx, int dy) {
        if (dx == 0 && dy == 0) return;

        final double cx = player.getSlayer().getBoundsInLocal().getWidth()  / 2;
        final double cy = player.getSlayer().getBoundsInLocal().getHeight() / 2;

        double x = cx + player.getSlayer().getLayoutX() + dx;
        double y = cy + player.getSlayer().getLayoutY() + dy;

        movePlayerTo(x, y);
    }

    public void movePlayerTo(double x, double y) {
        final double cx = player.getSlayer().getBoundsInLocal().getWidth()  / 2;
        final double cy = player.getSlayer().getBoundsInLocal().getHeight() / 2;

        if (x - cx >= 0 &&
                x + cx <= WIDTH &&
                y - cy >= 0 &&
                y + cy <= HEIGHT) {
            player.getSlayer().relocate(x - cx, y - cy);
            player.getSlayerHitbox().relocate(x - cx + 37, y - cy + 35);
        }
    }
public class Player {

    private int health;
    private int damage;
    private int stamina;
    private Image slayerImage;
    private ImageView slayer;
    private Rectangle slayerHitbox;
    boolean running, goUp, goDown, goRight, goLeft;

    public Player () {

        health = 5;
        damage = 1;
        stamina = 5;
        slayerImage = new Image("stick mob slayer.png", 100, 100, true, true);
        slayer = new ImageView(slayerImage);
        slayerHitbox = new Rectangle(10, 50);

    }

    public int getDamage() {
        return damage;
    }

    public void setDamage(int damage) {
        this.damage = damage;
    }

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public int getStamina() {
        return stamina;
    }

    public void setStamina(int stamina) {
        this.stamina = stamina;
    }

    public ImageView getSlayer() {
        return slayer;
    }

    public Rectangle getSlayerHitbox() {
        slayerHitbox.setFill(Color.TRANSPARENT);
        return slayerHitbox;
    }

}
public class Enemies {

    private int health;
    private int speed;
    private Image enemyImage;
    private ImageView enemy;
    private Rectangle enemyHitbox;
    Player player = new Player();

    public Enemies () {

        health = 1;
        speed = 1;
        enemyImage = new Image("stick enemy.png", 100, 100, true, true);
        enemy = new ImageView(enemyImage);
        enemyHitbox = new Rectangle(10, 50);
    }

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public ImageView getEnemy () {
        return enemy;
    }

    public Rectangle getEnemyHitbox() {
        enemyHitbox.setFill(Color.YELLOW);
        return enemyHitbox;
    }
}

This is everything I have done so far. I would appreciate any help. If possible I would like to know how to make the enemies appear from random spots of the borders of the screen as well. Thanks in advance.

Alexis676
  • 15
  • 1

1 Answers1

1

you should try first something more simple like implementing A* path search algo or some grid with some units on it before trying todo a game and having such questions

user8426627
  • 903
  • 1
  • 9
  • 19
  • Well, I didn't think it would be so hard so I told my teacher that I would make a game. Now I have one week to turn it in xd. – Alexis676 May 21 '19 at 17:25
  • @Alexis676: The complete example cited [here](https://stackoverflow.com/a/2353494/230513) shows an implementation. – trashgod May 21 '19 at 17:28
  • 1
    in realy simple case you dont need to calc exact vector, just like if char.x < enemy.x, enemy makes one step left, but its like no sign of some grid is in your code – user8426627 May 21 '19 at 17:32