Arrrgh! This is hopeless! My dream is to be a game developer, and I have tried to make a simple 2D game. Every single time, I tell you, every single time, I get stuck with something. Before my imageIO hasn't been working, so I decided to make a game with only javas Graphics2D. Just when I got started I encounter a problem, my game loop doesn't work. I use a simple Thread game loop. I put print messages in my code to debug that way. The loop runs once and then stop! Why?
Here is my code:
package shooter; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JPanel; public class GamePanel extends JPanel implements Runnable { private boolean paused = false; private boolean gameover = false; private int playerX, playerY, playerW, playerH, playerDx; private Thread thread; public GamePanel() { thread = new Thread(this); playerX = Game.WIDTH / 2 - 15; playerY = 360; playerW = 30; playerH = 20; addKeyListener(new KeyL()); thread.start(); } public void paint(Graphics gf) { Graphics2D g = (Graphics2D)gf; //paints the background. g.setColor(Color.BLACK); g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT); //paints the player g.setColor(Color.WHITE); g.fillRect(playerX, playerY, playerW, playerH); System.out.println("painted!"); } //game loop @Override public void run() { move(); repaint(); System.out.println("looped!"); try { Thread.sleep(17); }catch(Exception ex){ System.out.println(ex); } } //checks all collisions in game public void checkCollisions() { //checks if the player its the walls. if (playerX + playerDx < 0) { playerX = 0; playerDx = 0; } else if (playerX + playerDx > Game.WIDTH) { playerX = Game.WIDTH - playerW; playerDx = 0; } } //moves all entities. public void move() { playerX += playerDx; System.out.println("Moved!"); } private class KeyL extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_A) { playerDx = -2; System.out.println("moving left"); } if (key == KeyEvent.VK_D) { playerDx = 2; System.out.println("moving right"); } } } }
Yes, I know there is no main class. That one is in the JFrame class but I know the error isn't there.
This is very frustrating! Earlier I have just given up, but know I decided to get help instead.
Please, please, PLEASE, help me!
P.S. The controls doesn't work either.