I am currently working on a simple 2D graphics game. I just added collision detection and although it works, it returns ConcurrentModificationException
.
These are the errors I get.
My game also doesn't pause when the mouse exits the screen. Moreover, whenever a collision happens there is also a 1/2 to 1 second lag in the game which could be a result of the errors. Also, when I hit all of the bubbles, the bubbles do not continue to be drawn. Also, if you find any efficiency mistakes, please let me know. I have included the relevant code below. Thank you so much.
public class Game extends JPanel{
public static final int WINDOW_WIDTH = 600;
public static final int WINDOW_HEIGHT = 400;
private boolean insideCircle = false;
private static boolean ifPaused = false;
private static JPanel mainPanel;
private static JLabel statusbar;
private static int clicks = 0;
public static Bubbles[] BubblesArray = new Bubbles[5];
public static List<Bubbles> bubbles = new ArrayList<Bubbles>();
public Game() {
for (int i = 0; i < 10 ; i++){
bubbles.add(new Bubbles());
}
}
public void paint(Graphics graphics) {
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
if (!ifPaused){
for(Bubbles b : bubbles) b.paint(graphics);
}
}
public void update() {
if (!ifPaused){
for (Bubbles b : bubbles) b.update();
}
}
public static void main(String[] args) throws InterruptedException {
statusbar = new JLabel("Default");
Game game = new Game();
JFrame frame = new JFrame();
game.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
statusbar.setText(String.format("Your mouse is at %d, %d", e.getX(), e.getY()));
for (Bubbles b : bubbles)
{
int x = b.getX();
int y = b.getY();
int r = b.getCircleSize();
if ( (e.getX() >= (x - r/2) && e.getX() <= (x+ r/2)) && (e.getY() >= (y - r/2) && e.getY() <= (y+ r/2)) ){
//System.out.println("Inside");
bubbles.remove(b);
}
}
}
public void mouseExited(MouseEvent e){
ifPaused = true;
}
public void mouseEntered(MouseEvent e){
ifPaused = false;
}
});
frame.add(game);
frame.add(statusbar, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Bubble Burst");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
while (true) {
if (!ifPaused){
game.update();
game.repaint();
Thread.sleep(5);
}
}
}
}