lr-core
Version:
Line Rider core library
105 lines (88 loc) • 2.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getCellsFromLine = require('./getCellsFromLine.js');
var _hashNumberPair = require('../../utils/hashNumberPair.js');
var _subclassable = require('../../subclassable');
var _orderedObjectArray = require('../../ordered-object-array');
var _orderedObjectArray2 = _interopRequireDefault(_orderedObjectArray);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const GRID_SIZE = 14;
class LineCellsMap extends _subclassable.SubclassableMap {
add(line, cells) {
this.set(line.id, cells);
}
remove(line) {
let cells = this.get(line.id);
if (!cells) return [];
this.delete(line.id);
return cells;
}
}
class CellLinesMap extends _subclassable.SubclassableMap {
add(line, cells) {
for (let cell of cells) {
let cellLines = this.get(cell);
if (!cellLines) {
cellLines = new _orderedObjectArray2.default('id', true);
this.set(cell, cellLines);
}
cellLines.add(line);
}
}
remove(line, cells) {
for (let cell of cells) {
let cellLines = this.get(cell);
cellLines.remove(line);
if (cellLines.length === 0) {
this.delete(cell);
}
}
}
}
// handles collidable lines in 6.2 physics
class ClassicGrid {
constructor(getCellFn = _getCellsFromLine.classicCells) {
this.getCellsFromLine = getCellFn;
this.lineCellsMap = new LineCellsMap();
this.cellLinesMap = new CellLinesMap();
}
add(line) {
if (!line.collidable) return [];
let cells = this.getCellsFromLine(line, GRID_SIZE);
this.lineCellsMap.add(line, cells);
this.cellLinesMap.add(line, cells);
return cells;
}
remove(line) {
let cells = this.lineCellsMap.remove(line);
this.cellLinesMap.remove(line, cells);
}
// 3x3 grid around entity
getCellsNearEntity(entity) {
let gx = Math.floor(entity.pos.x / GRID_SIZE);
let gy = Math.floor(entity.pos.y / GRID_SIZE);
let cells = [];
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
cells.push((0, _hashNumberPair.hashIntPair)(i + gx, j + gy));
}
}
return cells;
}
// the lines in the 3x3 grid around entity, with duplicates
getLinesNearEntity(entity) {
let lines = [];
let cells = this.getCellsNearEntity(entity);
for (let cell of cells) {
let cellLines = this.cellLinesMap.get(cell);
if (!cellLines) continue;
for (let line of cellLines) {
lines.push(line);
}
}
return lines;
}
}
exports.default = ClassicGrid;