hi @harvious,
Adding to Jeremy’s answer (and questions):
- Do the balls are objects of similar sizes ?
If so, spatial hashing could be a solution.
The “giCentre” library has a powerful HashGrid
class (see example) but it will return the points within a radius of a specific location (not within a bounding box).
Processing has a HashMap()
class (see reference) but I don’t know Java well and can’t tell if you could use it in this case.
You could also try to implement your own class based on the various examples you can find on the web. Here below a simple example sketch in Python mode that just does that:
5000 points bouncing in a 2D space (GIF)
Script
def setup():
size(800, 400, P3D)
frameRate(1000)
strokeWeight(2)
textSize(9)
smooth(8)
global hmap, cellSize, balls
cellSize = int(width/20)
hmap = Hashmap()
balls = [Ball() for i in xrange(1000)]
def draw():
background('#ffffff')
for b in balls:
b.update()
b.render()
hmap.insert(b.loc)
pushStyle()
strokeWeight(1)
stroke('#ffffff')
for x in xrange(0, width, cellSize):
for y in xrange(0, height, cellSize):
binPts = hmap.query(PVector(x, y))
fill(10 + len(binPts) * 7, 250 - len(binPts) * 3, 255 - len(binPts) * 2, 130)
rect(x, y, cellSize, cellSize)
fill('#0000')
text(len(binPts), x + cellSize * .1, y + cellSize * .9)
popStyle()
hmap.reset()
class Ball(object):
def __init__(self):
self.loc = PVector(random(width), random(height), 0)
self.vel = PVector.random2D()
def update(self):
self.loc.add(self.vel)
if self.loc.x > width or self.loc.x < 0: self.vel.x *= -1
if self.loc.y > height or self.loc.y < 0: self.vel.y *= -1
def render(self):
point(self.loc.x, self.loc.y, self.loc.z)
class Hashmap(object):
def __init__(self):
self.grid = {}
def _key(self, p):
return (int((floor(p.x/cellSize))*cellSize),
int((floor(p.y/cellSize))*cellSize),
int((floor(p.z/cellSize))*cellSize))
def insert(self, p):
if self._key(p) not in self.grid:
self.grid[self._key(p)] = []
self.grid.setdefault(self._key(p), []).append(p)
def query(self, p):
return self.grid.setdefault(self._key(p), [])
def reset(self):
self.grid = {}