简单的问题。我试图重新制作游戏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){}
}
答案 0 :(得分:1)
答案 1 :(得分:0)
使用keyPressed()
方法条件逻辑的结构,您需要在keyReleased()
中进行类似的检查,以确定在设置任何一个paddle的速度之前释放了哪个键。实际上,您可以释放任意键,keyReleased()
会将p1和p2的值分配为零。</ p>