I have begun the process of teaching myself java game design, and I have run into my first obstacle: I have a KeyListener object which is called right now when the user clicks the right or left keys. When it is called I am having the console print "this works", and I am updating vel to 1 or -1. However, while the console is printing vel will not update. Why is this?
public class Paddle{
private int width = 100;
private int height = 15;
private int winWidth;
private int posX;
private int posY;
int vel = 0;
Game game;
public Paddle(){
}
public Paddle(int winWidth, int winHeight, Game game){
posX = winWidth / 2;
posY = winHeight - 70;
this.winWidth = winWidth;
this.game = game;
}
**public void move(){
if((posX + vel < winWidth) && (posX + vel > 0)){
posX += vel;
}
}**
public void paint(Graphics2D g){
g.setColor(Color.BLACK);
g.fillRect(posX, posY, width, height);
}
**public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
System.out.println("This works");
this.vel = 1;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
vel = -1;
}
}
public void keyReleased(KeyEvent e) {
vel = 0;
}**
}
.
public class Keyboard implements KeyListener{
Paddle paddle = new Paddle();
@Override
public void keyPressed(KeyEvent e) {
paddle.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
paddle.keyReleased(e);
}
@Override
public void keyTyped(KeyEvent e) {
//Not using it
}
}
.
public class Game extends JPanel{
public int width = 900;
public int height = width / 16 * 9;
private static boolean running = true;
Ball ball = new Ball(width, height, this);
Paddle paddle = new Paddle(width, height, this);
Keyboard keyboard = new Keyboard();
public Game(){
JFrame frame = new JFrame("Mini Tennis");
this.addKeyListener(keyboard);
this.setFocusable(true);
frame.add(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);;
frame.setLocationRelativeTo(null);
System.out.println(frame.getHeight());
}
public void move(){
ball.move();
paddle.move();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
ball.paint(g2d);
paddle.paint(g2d);
}
public void gameOver(){
running = false;
System.out.println("Game Over");
}
public static void main(String[] args) throws InterruptedException{
Game game = new Game();
while(running){
game.move();
game.repaint();
Thread.sleep(10);
}
}
}