Repository navigation
Expand file tree
/
Copy pathspatialHash.js
More file actions
59 lines (50 loc) · 1.89 KB
/
Copy pathspatialHash.js
File metadata and controls
59 lines (50 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class SpatialHash {
constructor(cellSize = 50) {
this.cellSize = cellSize;
this.grid = new Map();
this.particlePositions = [];
}
clear() {
this.grid.clear();
this.particlePositions = [];
}
insert(index, x, y) {
this.particlePositions[index] = [x, y];
const cellX = Math.floor(x / this.cellSize);
const cellY = Math.floor(y / this.cellSize);
const key = `${cellX},${cellY}`;
if (!this.grid.has(key)) {
this.grid.set(key, []);
}
this.grid.get(key).push(index);
}
findNeighbors(x, y, radius) {
const results = [];
const minCellX = Math.floor((x - radius) / this.cellSize);
const maxCellX = Math.floor((x + radius) / this.cellSize);
const minCellY = Math.floor((y - radius) / this.cellSize);
const maxCellY = Math.floor((y + radius) / this.cellSize);
for (let cellX = minCellX; cellX <= maxCellX; cellX++) {
for (let cellY = minCellY; cellY <= maxCellY; cellY++) {
const key = `${cellX},${cellY}`;
const cellParticles = this.grid.get(key);
if (cellParticles) {
for (let idx of cellParticles) {
const [px, py] = this.particlePositions[idx];
const dist = Math.hypot(px - x, py - y);
if (dist < radius) {
results.push({ index: idx, x: px, y: py, dist: dist });
}
}
}
}
}
return results;
}
getParticleInCell(x, y) {
const cellX = Math.floor(x / this.cellSize);
const cellY = Math.floor(y / this.cellSize);
const key = `${cellX},${cellY}`;
return this.grid.get(key) || [];
}
}