Advertisement
Tkap1

Untitled

Nov 24th, 2023 (edited)
624
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function addToQuadTree(tree, entity)
  2. {
  3.     if(!rectCollidesRect(tree.pos, tree.size, entity.pos, entity.size)) {
  4.         return false;
  5.     }
  6.     if(tree.elements.length < tree.capacity) {
  7.         tree.elements.push(entity);
  8.         return true;
  9.     }
  10.     else {
  11.         if(!tree.children) {
  12.             tree.children = [];
  13.             let child0 = new QuadTree();
  14.             let child1 = new QuadTree();
  15.             let child2 = new QuadTree();
  16.             let child3 = new QuadTree();
  17.  
  18.             child0.pos.x = tree.pos.x;
  19.             child0.pos.y = tree.pos.y;
  20.             child0.pos.size.x = tree.size.x / 2;
  21.             child0.pos.size.y = tree.size.y / 2;
  22.  
  23.             child1.pos.x = tree.pos.x + tree.size.x / 2;
  24.             child1.pos.y = tree.pos.y;
  25.             child1.pos.size.x = tree.size.x / 2;
  26.             child1.pos.size.y = tree.size.y / 2;
  27.  
  28.             child2.pos.x = tree.pos.x;
  29.             child2.pos.y = tree.pos.y + tree.size.y / 2;
  30.             child2.pos.size.x = tree.size.x / 2;
  31.             child2.pos.size.y = tree.size.y / 2;
  32.  
  33.             child3.pos.x = tree.pos.x + tree.size.x / 2;
  34.             child3.pos.y = tree.pos.y + tree.size.y / 2;
  35.             child3.pos.size.x = tree.size.x / 2;
  36.             child3.pos.size.y = tree.size.y / 2;
  37.  
  38.             tree.children.push(child0);
  39.             tree.children.push(child1);
  40.             tree.children.push(child2);
  41.             tree.children.push(child3);
  42.         }
  43.         for(let i = 0; i < 4; i += 1) {
  44.             if(addToQuadTree(tree.children[i], entity)) {
  45.                 return true;
  46.             }
  47.         }
  48.     }
  49.     return false;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement