在java中按左箭头键时,形状不在正确的位置

时间:2016-02-15 02:35:16

标签: java android swing netbeans awt

我有这个pacman游戏。它已经在工作,但我有其他形状的问题,特别是pacman的眼睛。问题是,当我按向左和向上箭头键时,眼睛的位置得到错误的位置。见附图

有人可以帮我解决这个问题。这是我的代码。

 public void paintComponent(Graphics graphics)
    {
        super.paintComponent(graphics);

        //pacman
        graphics.setColor(Color.yellow);
        graphics.fillArc(xLocation, yLocation, 100, 100, angle, mouth);

        //eyes
        graphics.setColor(Color.BLACK);
        graphics.fillOval(xLocationEyes, yLocationEyes, 20, 20);
        food(graphics);
    }
 @Override
 public void keyPressed(KeyEvent keyboard) {


int keyboardPress = keyboard.getKeyCode();
         if(keyboardPress == KeyEvent.VK_RIGHT){
             if(xLocation + 130 >= getWidth()){
                 xLocationEyes = getWidth()-130;
                 xLocation = 600-160;
             }

             xLocation += 30;
             xLocationEyes += 30;
             angle = 45;
             repaint();
     }
 if(keyboardPress == KeyEvent.VK_LEFT){

         if(xLocation  <= 0){
             xLocationEyes = 45;
             xLocation = 30;

         }
         angle = -145;
         xLocation -= 30;            
         xLocationEyes -= 30;
         repaint();

     }
}

1 个答案:

答案 0 :(得分:1)

Pac-Man,我最喜欢的街机游戏之一,脸部不是对称的。当您在水平轴上翻转身体时,您还需要翻转他的眼睛。这主要是一些修补你的数字,但是当你调用以下代码行时

if(keyboardPress == KeyEvent.VK_LEFT){

      //i dont know what this does so tread at your own will
     if(xLocation  <= 0){
         xLocationEyes = 45;
         xLocation = 30;

     }

     angle = -145;
     xLocation -= 30;   
     //tinker with this value and the value of you moving the eye back when moving right         
     xLocationEyes += 30; //note the += this may fix your issue
     repaint();

 }