3

I'm currently developing a simulation involving several thousand 1x1 pixel 2D Rectangles moving around a JPanel. The rectangles move and can collide and join together.

I have created an Event Dispatch Thread which in turn creates my GUI. I am then creating an instance of the simulation and using a game-loop to control the system with move(), detectCollision() and repaint() methods, with all of the rectangles stored in a global ArrayList. move() shifts each rectangle by 1 pixel while detectCollision() checks to see if two rectangles are next to each other and joins them together if applicable.

The system currently works, however it runs incredibly slowly. Placing a timer around each method showed that my detectCollision() method can take up to 1000ms to complete. My question is, can I use a worker thread inside the detectCollision() method to improve the efficiency of the program?

2 Answers2

2

Broad-phase algorithm

  • It is any algorithm to limit the number of pairs to be checked for collision in a simulation system.

  • If you are performing n^2 collision checks, you need a broad-phase algorithm.

  • Since your objects are already rectangles, I think some space partitioning technique should help you.

Resource: Broad-phase collision detection methods?

In most application, I have seen an efficient broad-phase algorithm reduce the time taken by orders of magnitude. But of course that varies with the situation.

Good luck.

Community
  • 1
  • 1
Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45
2

To deal with computationally intensive simulations, applications generally divide the work into two domains: the graphics engine, including your JPanel's subsclass's #repaint() ; the simulation engine which would contain the #move() and #detectCollision() methods.

The simulation would be run within it's own Thread, updating the displayable state via graphics engine using SwingUtilities#invokeLater method. The simulation generally attempts to achieve a certain number of simulation ticks per second, sleeping in between.

Generally an Event Dispatcher Thread (EDT) is created inside the native AWT to digest events arriving from the underlying windowing system. If you are manually creating this somehow it's sign you are probably using Swing or AWT incorrectly.

Mark
  • 1,128
  • 13
  • 21