简单的问题。我正在尝试重新创建Pong游戏。我已经在屏幕上得到了想要的图形,并且两个按键与KeyEvents一起移动了。我唯一的问题是,当我释放一个键时,另一个拨片也将停止(如果两个拨片都同时移动),我确切地知道为什么会发生这种情况,但无法找出解决方法。发生这种情况的原因是,当调用keyReleased方法时,两个桨都设置为速度0。如何在使用keyReleased方法分别移动/停止两个桨的地方进行不同的编码?
码:
package pong.main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PongGame extends JPanel implements ActionListener,KeyListener {
private final int WIDTH = 750;
private final int HEIGHT = 750;
private int DELAY = 20;
private int IMAGE_SIZE = 35;
private ImageIcon paddle_one;
private ImageIcon paddle_two;
private ImageIcon pong_logo;
private ImageIcon pong_ball;
private Timer timer = new Timer(DELAY, this);
private int p1_x = 10;
private int p1_y = 325;
private int p2_x = 710;
private int p2_y = 325;
private int p1_moveX;
private int p1_moveY;
private int p2_moveX;
private int p2_moveY;
public PongGame(){
timer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
paddle_one = new ImageIcon("C:\\Users\\Bryan\\Pictures\\paddle.gif");
paddle_two = new ImageIcon("C:\\Users\\Bryan\\Pictures\\paddle.gif");
pong_logo = new ImageIcon("C:\\Users\\Bryan\\Pictures\\pong_logo.gif");
pong_ball = new ImageIcon("C:\\Users\\Bryan\\Pictures\\pong_ball.gif");
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.black);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
paddle_one.paintIcon(this, g, p1_x, p1_y);
paddle_two.paintIcon(this, g, p2_x, p2_y);
pong_ball.paintIcon(this, g, 350, 350);
pong_logo.paintIcon(this, g, 220, -100);
}
public void actionPerformed(ActionEvent e){
repaint();
p1_x += p1_moveX;
p1_y += p1_moveY;
p2_x += p2_moveX;
p2_y += p2_moveY;
}
public void paddle_one_up(){
p1_moveX = 0;
p1_moveY = -5;
}
public void paddle_one_down(){
p1_moveX = 0;
p1_moveY = 5;
}
public void paddle_two_up(){
p2_moveX = 0;
p2_moveY = -5;
}
public void paddle_two_down(){
p2_moveX = 0;
p2_moveY = 5;
}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if(code == KeyEvent.VK_W){
paddle_one_up();
}
if(code == KeyEvent.VK_S){
paddle_one_down();
}
if(code == KeyEvent.VK_UP){
paddle_two_up();
}
if(code == KeyEvent.VK_DOWN){
paddle_two_down();
}
}
public void keyReleased(KeyEvent e){
int code = e.getKeyCode();
if(code != KeyEvent.VK_W){
p1_moveX = 0;
p1_moveY = 0;
}
if(code != KeyEvent.VK_S){
p1_moveX = 0;
p1_moveY = 0;
}
if(code != KeyEvent.VK_UP){
p2_moveX = 0;
p2_moveY = 0;
}
if(code != KeyEvent.VK_DOWN){
p2_moveX = 0;
p2_moveY = 0;
}
public void keyTyped(KeyEvent e){}
}
最佳答案
查看您的keyPressed方法和keyReleased方法之间的区别。
在keyReleased中执行类似的操作-检查KeyEvent对象的键代码并采取相应的措施。这两种方法之间的差异以及您无法解决此问题表明您的keyPressed代码是借来的代码。只要您先理解代码就可以借用代码。最好借用想法,然后编写自己的代码。
甚至更好-使用Key Bindings是比使用KeyListeners更安全,更好的解决方案。