In the development of my game, I have reached a critical juncture where an effective collision detection system is imperative. Currently, I am utilizing a complex array containing 1s and 0s to designate boundaries.
To streamline this process, I have created a basic grid tool that highlights specific cells indicating boundary areas. However, I am facing challenges in simplifying the output for faster access.
My plan involves restructuring the boundaries based on consecutive highlighted cells while leaving out entries for non-highlighted cells, essentially creating a sparse matrix.
For example, with a cell size of 10: 0,0 [_ _ ]- - -[ _ _]
The expected output would be:
{ x: [0,30], y: [0,10] },
{ x: [60,90], y: [0,10] }
However, instead of obtaining this desired result, I end up with empty objects for each cell.
The code snippet below illustrates my attempt at merging the ranges of highlighted cells into a singular object representing 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;
}