quadtree-js dynamic example

Total Objects: 0
Candidates: 0 (0%)

This example demonstrates the usage for a dynamic system. All objects are constantly moving. The quadtree is regenerated with each game loop.

We start off with an empty tree.

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

Next, lets create some objects. Objects that we plan to insert into the quadtree need x, y, width and height properties in order to work.

You can add as many other properties as you like. In this example, we use custom properties vx, vy and check.

var myObjects = [];

for(var i=0;i<200;i=i+1) {
	myObjects.push({
		x: randMinMax(0, 640),
		y: randMinMax(0, 480),
		width: randMinMax(10, 20),
		height: randMinMax(10, 20),
		vx: randMinMax(-0.5,0.5),
		vy: randMinMax(-0.5,0.5),
		check: false
	});
}

We will clear and rewrite the quadtree with every game loop. This is neccessary to keep the tree clean and accurate (due to its recursive nature).

function loop() {

	//remove all objects and subnodes 
	myTree.clear();

	//update myObjects and insert them into the tree again
	for(var i=0;i<myObjects.length;i=i+1) {
		
		myObjects[i].x += myObjects[i].vx;
		myObjects[i].y += myObjects[i].vy;
		
		myTree.insert(myObjects[i]);
	}

	//call next frame
	requestAnimationFrame(loop);
}

After filling the quadtree, we can now retrieve collision candidates for a certain area. 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;
}

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