【问题标题】:Shape is not in the right position when pressing left and arrow key in java在java中按左键和箭头键时形状不在正确的位置
【发布时间】:2016-02-15 02:35:16
【问题描述】:

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

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

 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();

     }
}

【问题讨论】:

  • 只根据方向改变眼睛的位置
  • @MadProgrammer 我试过了,但是两个形状(pacman 和他的眼睛)没有同步。
  • @MadProgrammer 你能在这里提供一些样本吗?欣赏它。
  • 如需尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example
  • @AndrewThompson 你对此有什么建议吗?

标签: java android swing netbeans awt


【解决方案1】:

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

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();

 }

【讨论】:

  • 只要修改 eye x 值,你最终会得到它
  • 是的,它适用于第一次印刷。但由于它的 + 它会向右移动,所以眼睛向右移动..
  • 这里有任何其他解决方案
猜你喜欢
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
相关资源
最近更新 更多