I am working on a game and I’ve come to the point where I am in need of an efficient collision detection system. At the moment, I am using a very heavy handed array of 1 and 0 to indicate a boundary.
I’ve written a crude grid creation tool that allows me to highlight the cells that I would like to indicate have a boundary however, I’m a bit lost in terms of how to simplify the output for quicker access.
Currently, my intention is to restructure the boundaries based on if there are consecutive highlighted cells and no entries when there are no highlighted cells. Hence the sparse matrix.
For example, assuming a cell size of 10
0,0
[_ _ ]- – -[ _ _]
I would expect my ouput to be
{ x: [0,30], y: [0,10] },
{ x: [60,90], y: [0,10] }
At the moment, I get an empty object for each cell..
This is the current iteration of my attempt to merge the range of the highlighted cells in to a single object to represent a boundary.
function mergeConsecutiveCells(boundaries) {
const mergedBoundaries = [];
if (boundaries.length === 0) {
return mergedBoundaries;
}
boundaries.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
let currentBoundary = boundaries[0];
for (let i = 1; i < boundaries.length; i++) {
const nextBoundary = boundaries[i];
if (
currentBoundary[1] === nextBoundary[1] &&
currentBoundary[2] === nextBoundary[2] &&
currentBoundary[3] === nextBoundary[3] &&
currentBoundary[0] + cellSize === nextBoundary[0]
) {
// Consecutive cells, extend the range
currentBoundary[0] = nextBoundary[0];
} else {
// Non-consecutive cells, add the current boundary to the result
mergedBoundaries.push({
x: { start: currentBoundary[0], end: currentBoundary[0] + cellSize },
y: { start: currentBoundary[1], end: currentBoundary[3] }
});
currentBoundary = nextBoundary;
}
}
// Add the last boundary
mergedBoundaries.push({
x: { start: currentBoundary[0], end: currentBoundary[0] + cellSize },
y: { start: currentBoundary[1], end: currentBoundary[3] }
});
return mergedBoundaries;
}
