Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function addToQuadTree(tree, entity)
- {
- if(!rectCollidesRect(tree.pos, tree.size, entity.pos, entity.size)) {
- return false;
- }
- if(tree.elements.length < tree.capacity) {
- tree.elements.push(entity);
- return true;
- }
- else {
- if(!tree.children) {
- tree.children = [];
- let child0 = new QuadTree();
- let child1 = new QuadTree();
- let child2 = new QuadTree();
- let child3 = new QuadTree();
- child0.pos.x = tree.pos.x;
- child0.pos.y = tree.pos.y;
- child0.pos.size.x = tree.size.x / 2;
- child0.pos.size.y = tree.size.y / 2;
- child1.pos.x = tree.pos.x + tree.size.x / 2;
- child1.pos.y = tree.pos.y;
- child1.pos.size.x = tree.size.x / 2;
- child1.pos.size.y = tree.size.y / 2;
- child2.pos.x = tree.pos.x;
- child2.pos.y = tree.pos.y + tree.size.y / 2;
- child2.pos.size.x = tree.size.x / 2;
- child2.pos.size.y = tree.size.y / 2;
- child3.pos.x = tree.pos.x + tree.size.x / 2;
- child3.pos.y = tree.pos.y + tree.size.y / 2;
- child3.pos.size.x = tree.size.x / 2;
- child3.pos.size.y = tree.size.y / 2;
- tree.children.push(child0);
- tree.children.push(child1);
- tree.children.push(child2);
- tree.children.push(child3);
- }
- for(let i = 0; i < 4; i += 1) {
- if(addToQuadTree(tree.children[i], entity)) {
- return true;
- }
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement