Simple Spatial Partitioning Class
in
Programming Questions
•
11 months ago
I'm working on a sketch that needs to do collision detection for hundreds (or possibly thousands) of particles, so in an effort to optimize it I decided to try a spatial partitioning algorithm. I was surprised that I couldn't find any good (simple) examples; everything was either O(n^2) collision detection or jumped straight to Quadtrees. I thought that something in the middle would be a good place to start, and hopefully a good example for others to learn from.
Here's the code:
However, getting things to work with the 2D ArrayList is a bit tricky. I'm currently stumped with an error occuring at line 33:
"The type of expression must be an array type but it resolved to ArrayList"
This seems to be because I can't use double indices for ArrayLists. Do I need to get() a sublist and then place the element in the subList? If that's the case, then do I need to replace the list with the new one also?
Is there a way to add a particle to a bin in-place, or is the only way to do it by copying the subarray and copying it back in?
thanks!
Here's the code:
- class Grid {
- float binSize;
- int noBinsX;
- int noBinsY;
- ArrayList[] particleBuckets = new ArrayList[noBinsY];
- Grid(float _binSize, int windowWidth, int windowHeight) {
- binSize = _binSize;
- noBinsX = ceil(windowWidth / _binSize);
- noBinsY = ceil(windowHeight / _binSize);
- //Setup the 2D ArrayList for the grid
- for(int i = 0; i < noBinsY; i++) {
- particleBuckets[i].add(new ArrayList<Particle>(noBinsX));; }
- }
- void getParticles(int binX, int binY) {
- ArrayList subList = particleBuckets.get(binY);
- return subList.get(binX);
- }
- int[] getBinNumber(float pos_x, float pos_y) {
- //given a particle's position, return the bin number that it is currently in.
- int indexX = floor(pos_x / binSize);
- int indexY = floor(pos_y / binSize);
- int[] binNumbers = {indexX,indexY};
- return binNumbers;
- }
- void addParticle(Particle particle) {
- //Add a new particle to the grid.
- int indexX = floor(particle.pos_x / binSize);
- int indexY = floor(particle.pos_y / binSize);
- particleBuckets[clamp(indexY,0,noBinsY - 1)][clamp(indexX,0,noBinsX - 1)].add(particle);
- }
- }
- int clamp(int value, int minVal, int maxVal) {
- return max(minVal, min(value,maxVal));
- }
However, getting things to work with the 2D ArrayList is a bit tricky. I'm currently stumped with an error occuring at line 33:
"The type of expression must be an array type but it resolved to ArrayList"
This seems to be because I can't use double indices for ArrayLists. Do I need to get() a sublist and then place the element in the subList? If that's the case, then do I need to replace the list with the new one also?
Is there a way to add a particle to a bin in-place, or is the only way to do it by copying the subarray and copying it back in?
thanks!
1