toJSON
方法返回一个表示当前CellSpacePartitioning
实例的JSON对象。
cellSpacePartitioningInstance.toJSON();
返回一个JSON对象,其中包含以下属性:
属性名 | 类型 | 描述 |
---|---|---|
numCells |
number |
全部单元格的数量。 |
numObjects |
number |
该空间分割对象所包含的所有物体的数量。 |
cellSize |
number |
单元格的宽度和高度,以像素为单位。 |
cells |
Array |
所有单元格的数组。每个单元格对象包含以下属性:x,y,left,top,right,bottom,objectList 。其中,x 和y 表示单元格的坐标,使用类似网格一样的索引。left ,top ,right 和bottom 表示单元格在空间中的范围,以像素为单位。objectList 是一个包含该单元格内所有物体的数组。 |
const spacePartitioning = new CellSpacePartitioning(800, 600, 50, 50);
spacePartitioning.addObject({ x: 100, y: 200, radius: 20 });
spacePartitioning.addObject({ x: 300, y: 400, radius: 20 });
const json = spacePartitioning.toJSON();
console.log(json);
/*
{
"numCells": 196,
"numObjects": 2,
"cellSize": 50,
"cells": [
{
"x": 0,
"y": 0,
"left": 0,
"top": 0,
"right": 50,
"bottom": 50,
"objectList": []
},
{
"x": 1,
"y": 0,
"left": 50,
"top": 0,
"right": 100,
"bottom": 50,
"objectList": [
{
"x": 100,
"y": 200,
"radius": 20
}
]
},
{
"x": 2,
"y": 0,
"left": 100,
"top": 0,
"right": 150,
"bottom": 50,
"objectList": []
},
// 省略其它单元格的信息
{
"x": 13,
"y": 11,
"left": 650,
"top": 550,
"right": 700,
"bottom": 600,
"objectList": []
},
{
"x": 14,
"y": 11,
"left": 700,
"top": 550,
"right": 750,
"bottom": 600,
"objectList": []
},
{
"x": 15,
"y": 11,
"left": 750,
"top": 550,
"right": 800,
"bottom": 600,
"objectList": [
{
"x": 300,
"y": 400,
"radius": 20
}
]
}
]
}
*/
此示例创建了一个大小为800x600像素的空间分割对象,它使用50x50像素的单元格大小来管理物体。它向该空间分割对象添加2个物体,并使用toJSON
方法将其表示为JSON对象。该JSON对象显示所有单元格及其中包含的物体。