quadtree-js simple example

Total Objects: 0
Candidates: 0 (0%)

This quadtree starts off empty. Click the buttons to add elements to the Quadtree.

After adding five objects to the Quadtree it will split, because we initially set max_objects to 4.

var myTree = new Quadtree({
	x: 0,
	y: 0,
	width: 640,
	height: 480
}, 4);

Objects that you insert into the tree need to have x, y, width and height properties in order to work. Of course you can extend these objects with your own data.

var myObject = {
	x: 200,
	y: 100,
	width: 35,
	height: 70
}

myTree.insert(myObject);

In this example, we constantly retrieve collision candidates for the white area at your mouse cursor. The candidates are highlighted in green.

var myCursor = {
	x: mouseX,
	y: mouseY,
	width: 20,
	height: 20
};

var candidates = myTree.retrieve(myCursor);

The object passed to the retrieve function does not have to be inside the quadtree. It could be though, if that's your thing.

What you get is an array of your collision candidates. In this example, we will only mark them with a check-property to paint them green. In a real world example, you may want to check them for collisions.

for(var i=0;i<candidates.length;i=i+1) {
	candidates[i].check = true;
}

Run clear() to remove all objects from the quadtree and reset it.

myTree.clear();

To see the full example code please check the page source or visit GitHub.