实现原理 四叉树是什么? 四叉树本身是树结构的一种,如果物体过多的话,先根据物体所处位置划分成四块,如果每个块的中的物体数量还是很多的话,继续划分成四块。如下图红线所示。
检测的时候,就是根据待测试对象的位置,去找属于哪个块,再把这个块中的物体告诉你。如下图中的绿色物体。
那么怎么实现四叉树呢?用好 github 就行了(误),搜了一下,找到一个库,直接拿来改改就行了。
GitHub - timohausmann/quadtree-js: A lightweight quadtree implementation for javascript
代码解析 构造函数 function Quadtree( bounds, max_objects, max_levels, level ) { this.max_objects = max_objects || 10; //每个区域可以容纳的最大对象数,超过就需要划分 this.max_levels = max_levels || 4; //最多划几层四叉树 this.level = level || 0; //当前树或子树的层,根为0 this.bounds = bounds; //bounds就是对象集,每个点包括x,y,width,height(有些实现是圆形,这个是矩形) this.objects = []; //属于当前节点的对象,不包括子节点的对象 this.nodes = []; //属于当前树的节点 }; 划分 当调用Insert函数向树中插入对象的时候,如果当前节点没有被划分过的时候,会判断节点的对象数是否超过的限制的max_objects,如果超过了的话当前节点就会调用这个split方法。
Quadtree.prototype.split = function() { var nextLevel = this.level + 1; var subWidth = Math.round( this.bounds.width / 2 ); var subHeight = Math.round( this.bounds.height / 2 ); var x = Math.round( this.bounds.x ); var y = Math.round( this.bounds.y ); //第一象限,和数学里的坐标轴一样,不过起点变了而已 this.nodes[0] = new Quadtree({ x : x + subWidth, y : y, width : subWidth, height : subHeight }, this.max_objects, this.max_levels, nextLevel); //第二象限 this.nodes[1] = new Quadtree({ x : x, y : y, width : subWidth, height : subHeight }, this.max_objects, this.max_levels, nextLevel); //第三象限 this.nodes[2] = new Quadtree({ x : x, y : y + subHeight, width : subWidth, height : subHeight }, this.max_objects, this.max_levels, nextLevel); //第四象限 this.nodes[3] = new Quadtree({ x : x + subWidth, y : y + subHeight, width : subWidth, height : subHeight }, this.max_objects, this.max_levels, nextLevel); }; ...