var SpatialHash = function(cellSize) {
this.idx = {};
this.cellSize = cellSize;
}
SpatialHash.prototype.insert = function(x, y, obj) {
var cell = [];
var keys = this.keys(x,y);
for(var i in keys) {
var key = keys[i];
if(key in this.idx) {
cell = this.idx[key];
} else {
this.idx[key] = cell;
}
if(cell.indexOf(obj) == -1)
cell.push(obj);
}
}
SpatialHash.prototype.query = function(x, y) {
var key = this.key(x, y);
if(this.idx[key] != undefined)
return this.idx[key];
return [];
}
SpatialHash.prototype.keys = function (x, y) {
var o = this.cellSize / 2;
return [this.key(x-o, y+0),
this.key(x-0, y+0),
this.key(x+o, y+0),
this.key(x-o, y+o),
this.key(x-0, y+o),
this.key(x+o, y+o),
this.key(x-o, y-o),
this.key(x-0, y-o),
this.key(x+o, y-o)];
}
SpatialHash.prototype.key = function(x, y) {
var cellSize = this.cellSize;
x = Math.floor(x/cellSize)*cellSize;
y = Math.floor(y/cellSize)*cellSize;
return x.toString() + ":" + y.toString();
}
Monday, July 04, 2011
Spatial Hash in Javascript, for 2D.
Subscribe to:
Post Comments (Atom)
Popular Posts
-
These are the robots I've been working on for the last 12 months. They each weigh about 11 tonnes and have a 17 meter reach. The control...
-
This hard-to-see screenshot is a Generic Node Graph Editing framework I'm building. I'm hoping it can be used for any kind of node...
-
Unfortunately I've not secured a venue for the GGJ. With 9 days left, things are not looking hopeful. It could be that GGJ Perth will no...
-
So, you've created a car prefab using WheelCollider components, and now you can apply a motorTorque to make the whole thing move along. ...
-
MiddleMan: A Pub/Sub and Request/Response server in Go. This is my first Go project. It is a rewrite of an existing Python server, based o...
-
Often, when building a game, you need to test if objects are colliding. The objects could be spaceships, rocks, mouse pointers, laser beams....
-
I've just read a newspaper article (courtesy of Kranzky ) from WA Business News documenting the malfeasance, gross negligence and misc...
-
After my last post, I decided to benchmark the scaling properties of Stackless, Kamaelia, Fibra using the same hackysack algorithm. Left axi...
-
I made something which lets you render very large worlds with a small farClipPlane. https://github.com/simonwittber/scaled-origin The d...
-
Space is awesome. Especially when it is generated using Perlin noise, and some cool shaders. You can try it out over here.
3 comments:
Thanks for bring oarsome. Can you maek a 3d version?
would be interesting to see a comparison of how different hash functions perform
This looks great! Sorry to bother, but I was wonderingif you have a working example\demo of this? I'm new to the whole Javscript development thing, and while I can just about follow this code, making that leap into an application is proving tricky!
Thanks in advance!:)
Post a Comment