how to do a diagonal movement

I’ve some problem with the sprite movements:
my intent is to do a diagonal movent by pressing the up and right/left key,
my code is:


public void keyPressed (KeyEvent event)
      {
       switch (event.getKeyCode())
            {
                case KeyEvent.VK_UP:
                                if (y > 0)
                                y -= JUMP;
                                break;               
               case KeyEvent.VK_DOWN:
                                if (y < APPLET_HEIGHT-IMAGE_SIZE)
                                y += JUMP;
                                break;
               case KeyEvent.VK_LEFT:
                                if (x > 0)
                                x -= JUMP;
                                break;                                
               case KeyEvent.VK_RIGHT:
                                if (x < APPLET_WIDTH-IMAGE_SIZE)
                                x += JUMP;
                                break;    
            }      
    
         repaint();
      }

what I’ve to change??

I think if the player presses the up key at the same time as the left key AWT will create 2 key events. One with up as the keycode and one with left as the keycode.

The only easy way to change it so you do not have to change your game design is to use different keys for diagonal movement(like using the numberpad or a block of six letters).

Maybe you can change your design so that you don’t generate a repaint request on every keypress. Instead repaint every x number of milli-seconds and in the code section that you posted just remove the repaint line, and all of the breaks.

Or, assuming this is an application and not an applet, drop AWT input alltogether and use JInput.

I’ve had great results in the past with handling input in such a way that I

  • collect all input first
  • apply input states to game
  • render game

every frame.

So I don’t start applying the input to the game until I am done collecting input for that frame. That way, you can just set flags or other state data (like VK_UP sets boolean upPressed = true, etc…), then process it all atomically.

I definitely agree you don’t want to repaint on every key press…

Just collect input for a given amount of time, then stop collecting input, update your game state, and repaint once. Rinse and repeat…

Enjoy!

I generally have a list of current buttons pressed that is added to on keyPressed and removed from on keyReleased. Then within the game loop I have a method to check the list of buttons pressed. Then it simply cycles through the list and checks for each button I might use induvidually – in your case, the arrow buttons.

In this way, if you are pressing up and right at the same time, there will be calls to both the up and right cases, resulting in a diagonal movement. Pressing left and right at the same time will have the two keys cancel each other out, resulting in no movement.

See what I’m saying?