quadtree-ts

2.2.2

Dynamic Example

This example demonstrates the usage for a dynamic system.

The quadtree is cleared and regenerated with each game loop. This is necessary due to the recursive nature of the Quadtree.

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,
});

// A Rectangle representing the mouse cursor
const myCursor = new Quadtree.Rectangle({
    x: 0,
    y: 0,
    width: 32,
    height: 32,
});

// Store all objects in an array
const myObjects = [];

// Create some objects
for(let i=0;i<200;i++) {
    const rectangle = new Quadtree.Rectangle({
        x: Math.random() * 640,
        y: Math.random() * 480,
        width: 4 + Math.random() * 28,
        height: 4 + Math.random() * 28,

        // Custom data: velocity for x and y, 
        // and a check boolean to flag retrieved objects
        data: {
            vx: -0.5 + Math.random(),
            vy: -0.5 + Math.random(),
            check: false,
        },
    });

    myObjects.push(rectangle);
}

// Main loop
function loop() {
    
    // Clear the tree
    tree.clear();
    
    // Update myObjects and insert them into the tree again
    myObjects.forEach(obj => {

        // Update the position
        obj.x += obj.data.vx;
        obj.y += obj.data.vy;

        // Reset retrieve flag
        obj.data.check = false;
        
        tree.insert(obj);
    });
    
    // Retrieve all objects that share nodes with the cursor
    const candidates = tree.retrieve(myCursor);

    // Flag retrieved objects
    candidates.forEach(obj => obj.data.check = true);

    // Draw scene
    draw();
    
    window.requestAnimationFrame(loop);
};

loop();

To see the full example code please check the page source or visit this page on github.