Skip to content

Instantly share code, notes, and snippets.

@troufster
Created November 22, 2010 19:45
Show Gist options
  • Select an option

  • Save troufster/710529 to your computer and use it in GitHub Desktop.

Select an option

Save troufster/710529 to your computer and use it in GitHub Desktop.
Javascript 2d spatial hash
var HashMap = function(cell_size) {
this.cell_size = cell_size;
this.grid = [];
}
HashMap.prototype._key = function(vec) {
var cellsize = this.cell_size;
return Math.floor(vec.x/cellsize) * cellsize + ' ' +
Math.floor(vec.y/cellsize) * cellsize;
}
HashMap.prototype.insert = function(ob) {
var obkey = this._key(ob.position);
var grid = this.grid;
if (!grid[obkey]) {
grid[obkey] = [];
}
grid[obkey].push(ob);
}
HashMap.prototype.getClosest = function(ob) {
return this.grid[this._key(ob.position)];
}
@DylanVann

Copy link
Copy Markdown

Grid should be an object, not an array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment