Update Example
This example demonstrates the usage of update.
It may be useful to only update single objects and not clear and regenerate the entire tree each time something changes, like in the dynamic example. Use this method when most objects are static (position/size never change).
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>
JS
// Create a new Quadtree
const tree = new Quadtree({
width: 640,
height: 480,
maxObjects: 9,
});
// Store all objects in an array
const myObjects = [];
let myCursor, myCircle;
// Add demo objects
createObjects();
loop();
// Main loop
function loop() {
// Update the circle position
myCircle.x = 320 + Math.cos(Date.now()/1000) * 176;
myCircle.y = 240 + Math.sin(Date.now()/1000) * 176;
// 👋 Call tree.update to remove and re-insert the object
// into the tree at current x, y values
tree.update(myCircle);
// Reset myObjects check property
myObjects.forEach(obj => {
obj.data.check = false;
});
// Retrieve all objects that share nodes with the cursor
if(isMouseover) {
const candidates = tree.retrieve(myCursor);
// Flag retrieved objects
candidates.forEach(obj => obj.data.check = true);
}
// Draw scene
draw();
window.requestAnimationFrame(loop);
};
createObjects() {
// A Rectangle representing the mouse cursor
myCursor = new Quadtree.Rectangle({
x: 0,
y: 0,
width: 32,
height: 32,
});
// Create some "static" objects
const cols = 6;
const rows = 6;
for(let x=0; x < cols; x++) {
for(let y=0; y < rows; y++) {
const rectangle = new Quadtree.Rectangle({
x: 72 + (x / cols) * (canvas.width-72),
y: 56 + (y / rows) * (canvas.height-56),
width: 16,
height: 16,
data: {
check: false,
},
});
myObjects.push(rectangle);
tree.insert(rectangle);
}
}
// Create a moving circle
myCircle = new Quadtree.Circle({
x: 32,
y: 240,
r: 32,
data: {
check: false,
},
});
myObjects.push(myCircle);
tree.insert(myCircle);
}
To see the full example code please check the page source or visit this page on github.