I've been trying to wrap my head around how to detect and fix collision at the moment but as I'm not very familiar with drawing on a JPanel I managed to mess up somehow. At the moment my loop looks like this:
import java.awt.*; import javax.swing.*; class GameLoop implements Runnable //This is the Game Loop, it controls all rendering and that. Use the getters/setters to change sprite stuff. { Thread thread = new Thread(this); Graphics g; private int x = 10, y = 10, a = 10, b = 10; private boolean hasCollided = false; Entity entity = new Entity(x, y, 20, 20); Entity entityTwo = new Entity(a, b, 20, 20); JPanel mainPanel; public GameLoop(JPanel mainPanel) { this.mainPanel = mainPanel; this.g = mainPanel.getGraphics(); } public void startThread() { thread.start(); } public void run() { while(true) { try { if(entity.getBounds().intersects(entityTwo.getBounds())) hasCollided = true; else hasCollided = false; if( hasCollided == false) { g.setColor(Color.red); g.fillRect(x, x, 20, 20); g.setColor(Color.blue); g.fillRect(a, b, 20, 20); } else if( hasCollided == true ) { g.setColor(Color.red); g.fillRect(x + 1, x + 1, 20, 20); entity.setX(x); entity.setY(y); g.setColor(Color.blue); g.fillRect(a, b, 20, 20); } mainPanel.repaint(); Thread.sleep(30); //Anything lower than 30 bugs out a little bit. This will run at something like 30FPS or something. } catch(Exception e) { e.printStackTrace(); //Prints where the exception occurs and some other info about it if an exception happens. } } } }
At line 8 I create the graphics object, then at line 18 I set it to the JPanel's graphics and then later on I use it to paint with. For some reason nothing is showing up on the JPanel.