【发布时间】:2021-05-19 14:41:26
【问题描述】:
我正在学习 java,并尝试创建一个小型乒乓球游戏作为对我的小测试,但我无法使右/左箭头键在我的代码中工作,我遵循了一些教程但仍然无法工作.
我的敌人和游戏中的球工作正常,一切都有碰撞,但我仍然无法使控件/键工作。
这是我正在使用的代码和我的 Player 类(我认为错误出在此处,但我仍然不知道如何找到它)。
代码
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
player.right = true;
else if(e.getKeyCode() == KeyEvent.VK_LEFT)
player.left = true;
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
player.right = false;
else if(e.getKeyCode() == KeyEvent.VK_LEFT)
player.left = false;
}
“玩家”类
public class Player {
public boolean right,left;
public int x,y;
public int width,height;
public Player(int x, int y) {
this.x = x;
this.y = y;
this.width = 40;
this.height = 10;
}
public void tick() {
if(right) {
x++;
}
else if(left) {
x--;
}
if(x+width > Game.WIDTH) {
x = Game.WIDTH - width;
}
else if(x < 0) {
x = 0;
}
}
public void Render(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, width,height);
}
}
【问题讨论】:
-
你在注册你的按键事件监听器吗?
-
我学习了一些教程你关注了这个tutorial 吗?
-
"(我认为错误在此处但我仍然不知道如何找到它)" 那是一个 我们敦促人们发布minimal reproducible example 的原因。根据定义,问题将出现在 MRE 中的某处。不要发布随机代码sn-ps。
标签: java swing awt keylistener