Property Mapping Example
In case you use other property names than the primitives' defaults
(e.g. x, y, width, height
),
you can map your properties.
The crucial part to make objects Quadtree-compatible is to implement the
Indexable interface –
that means to provide a qtIndex()
method, that returns the quadrant of the object
for any given Quadtree node. All Indexable objects can be inserted or used for retrieval.
The following code is reduced to the most important parts. View the full script.js of this example on GitHub.
HTML
<canvas id="canvas" width="640" height="480"></canvas>
Box.JS
// Custom Box class
class Box {
constructor(x, y, width, height) {
// This class describes rectangles with two vectors for position and size.
this.position = new Vector(x, y);
this.size = new Vector(width, height);
}
// In order to be a Quadtree compatible primitive
// your object has to implement the Indexable interface
// in form of a qtIndex method:
qtIndex(node) {
// The Box should act like a Rectangle
// so we just call qtIndex on the Rectangle prototype
// and map the position and size vectors to x, y, width and height
return Quadtree.Rectangle.prototype.qtIndex.call({
x: this.position.x,
y: this.position.y,
width: this.size.x,
height: this.size.y,
}, node);
}
draw(ctx) {
ctx.fillStyle = 'white';
ctx.fillRect(this.position.x, this.position.y, this.size.x, this.size.y);
}
}
Vector.JS
// Just a dummy Vector class
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
Script.JS
// Create a new Quadtree
const tree = new Quadtree({
width: 640,
height: 480,
maxObjects: 4,
});
// Store all objects in an array
const myObjects = [];
// Create a box every second
const interval = window.setInterval(() => {
const box = new Box(
Math.random() * (canvas.width-32),
Math.random() * (canvas.height-32),
4 + Math.random() * 28,
4 + Math.random() * 28,
);
tree.insert(box);
myObjects.push(box);
draw();
// Stop after 100 boxes
if(myObjects.length > 100) {
window.clearInterval(interval);
}
}, 1000);
To see the full example code please check the page source or visit this page on github.