我试图通过获取和设置x / y值来获得关键输入,但它不起作用

时间:2016-05-18 00:06:02

标签: java

我知道图像正在不断地绘制,但是x / y坐标没有变化,这不会让图像移动。为什么会发生这种情况,我该怎么做才能解决它

import java.awt.*;


public class GameState extends State {

  private Player player;
  private int playerX = 1440/2 - 14, playerY = 810/2 - 14;

  public GameState(SuperHexagonGame game)
  {
    super(game);
    player = new Player(playerX, playerY);
  }



  public void tick()
  {
    player.tick();
  }

  public Player getPlayer()
  {
    return player;
  }

  public void render(Graphics g)
  {
    g.drawImage(Assets.bg1, 0, 0, null);
    player.render(g);
  }
}

玩家类

import java.awt.*;


public class Player extends Creature {

  public Player(int x, int y)
  {
    super(x, y);
  }

  public void tick()
  {
  }

  public int getX()
  {
    return x;
  }
  public int getY()
  {
    return y;
  }
  public void setX(int x)
  {
    this.x = x;
  }
  public void setY(int y)
  {
    this.y = y;
  }

  public void render(Graphics g)
  {
    System.out.println(y);
    g.drawImage(Assets.player1, x, y, null);
  }

}

检查键输入的键输入类。我试图通过获取当前的xy值并添加/减去75来设置播放器类中的xy值

import java.awt.event.*;

public class KeyInput extends KeyAdapter {
  private Player player = new Player(1440 / 2 - 14, 810/2 - 14);
 public void keyPressed(KeyEvent e)
 {
   int key = e.getKeyCode();
   System.out.println(key);

   if (key == KeyEvent.VK_UP)
   {
     //decrement y by 75
     player.setY(player.getY() - 75);
   }
   if (key == KeyEvent.VK_DOWN)
   {
     //increment y by 75
   }
   if (key == KeyEvent.VK_LEFT)
   {
     //decrement x by 75
   }   
   if (key == KeyEvent.VK_RIGHT)
   {
     //increment x by 75
   }
 }
}

我知道程序正在获取键盘输入(箭头键),因为当按下某个键时,它会将键码显示到控制台中,但它不会将xy值设置为新的xy值以便移动。我只为完成箭头键完成了代码,因为我想确保它在复制粘贴之前有效。

1 个答案:

答案 0 :(得分:0)

这里有2 Player个。 Player player = new Player(1440 / 2 - 14, 810/2 - 14);player = new Player(playerX, playerY);

我会说,你正在编辑一个播放器并打印另一个播放器。尝试添加以下内容:

public class KeyInput extends KeyAdapter {
    private Player player;
    public KeyInput (Player player){
        this.player = player;    
    }
}