Skip to content

Commit

Permalink
feat: check collisions within the area (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
noih authored May 24, 2024
1 parent d11a84d commit 5f8a232
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/system.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,31 @@ describe("GIVEN System", () => {
expect(poly.dirty).toBe(false);
});

it("THEN checkArea() works", () => {
const { System } = require("../src");

const physics = new System();

const a = physics.createBox({ x: 10, y: 10 }, 100, 100);
const b = physics.createBox({ x: 300, y: 300 }, 100, 100);

let collisions = 0;

physics.checkArea({ minX: 0, minY: 0, maxX: 100, maxY: 100 }, () => {
collisions++;
});

expect(collisions).toBe(0);

b.setPosition(50, 50);

physics.checkArea({ minX: 0, minY: 0, maxX: 100, maxY: 100 }, () => {
collisions++;
});

expect(collisions).toBe(2);
});

describe("WHEN raycast is called", () => {
it("THEN works correctly on Ellipse", () => {
const { System } = require(".");
Expand Down
17 changes: 17 additions & 0 deletions src/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
intersectLinePolygon,
} from "./intersect";
import {
BBox,
Body,
BodyGroup,
BodyType,
Expand Down Expand Up @@ -95,6 +96,22 @@ export class System<TBody extends Body = Body> extends BaseSystem<TBody> {
return some(bodies, checkCollision);
}

/**
* check all bodies in area collisions with callback
*/
checkArea(
area: BBox,
callback: CollisionCallback = returnTrue,
response = this.response,
): boolean {
const bodies = this.search(area);
const checkOne = (body: TBody) => {
return this.checkOne(body, callback, response);
};

return some(bodies, checkOne);
}

/**
* check all bodies collisions with callback
*/
Expand Down

0 comments on commit 5f8a232

Please sign in to comment.