Search code examples
javajavafxjava-canvas

Moving an Image on Canvas with KeyPressed


My KeyPressed is working but there is no change in avatarDX from my moveLeft method. Did I do something wrong with moveLeft? It seems like it should be simple but I'm not sure what I did wrong. I don't have any error messages.

I'm drawing an image on a canvas with

gc.drawImage(avatar, avatarSX, avatarSY, avatarSW, avatarSH, avatarDX, avatarDY, avatarDW, avatarDH);

For KeyPressed I have

canvas.setOnKeyPressed(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent ke) {
            double speed = 2;
            switch(ke.getCode()) {
                case A:
                    System.out.println("pressed a");
                    moveLeft(avatarDX, speed);
                    System.out.println(avatarDX);
                    break;
            }
        }
});

And moveLeft is

private void moveLeft(double avatarDX, double speed) {
            while (avatarDX > 0) {
                avatarDX -= speed;
            }
        }

I would appreciate any help I am very new at this.


Solution

  • A reason (there may be others) the program doesn't act as you expect is that you are trying to process via a while loop to control your avatar.

    This will just pause the JavaFX application until the loop is completed and then update the screen to the final state at the end of the loop. JavaFX is not an immediate drawing system, it is a retained drawing system that only renders a scene when you cede control of the JavaFX application thread back to the JavaFX system.

    Instead, you need to use a callback to update the scene on each pulse.

    I suggest you use the following approach:

    1. As you are new at this, try writing the application using the JavaFX scene graph rather than a Canvas. Programming the scene graph is simply easier for many things. If, at a later stage, you find that Canvas is a better fit, then you can always convert to Canvas at that time when you better understand the JavaFX programming model.
    2. Review this sample of moving a character around the scene graph using key presses.
    3. Don't try to loop to move your character. Instead, either use the in-built high level JavaFX animation facilities such as transitions, or (when those aren't a good fit, as is likely the case here), use the low level AnimationTimer interface.
    4. Read up on game loops and JavaFX and apply the knowledge you learn there to your program.