Skip to content

Commit

Permalink
feature: only do collision check when needed (#314)
Browse files Browse the repository at this point in the history
  • Loading branch information
mflerackers authored Aug 4, 2024
1 parent de4ff16 commit 15e9992
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
35 changes: 27 additions & 8 deletions src/components/physics/area.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ import type { AnchorComp } from "../transform/anchor";
import type { FixedComp } from "../transform/fixed";
import type { PosComp } from "../transform/pos";

let areaCount = 0;

export function usesArea() {
return areaCount > 0;
}

/**
* The {@link area `area()`} component.
*
Expand Down Expand Up @@ -217,6 +223,7 @@ export function area(opt: AreaCompOpt = {}): AreaComp {
collisionIgnore: opt.collisionIgnore ?? [],

add(this: GameObj<AreaComp>) {
areaCount++;
if (this.area.cursor) {
this.onHover(() => app.setCursor(this.area.cursor!));
}
Expand All @@ -237,6 +244,10 @@ export function area(opt: AreaCompOpt = {}): AreaComp {
});
},

destroy() {
areaCount--;
},

update(this: GameObj<AreaComp>) {
for (const id in colliding) {
if (!collidingThisFrame.has(Number(id))) {
Expand Down Expand Up @@ -407,9 +418,11 @@ export function area(opt: AreaCompOpt = {}): AreaComp {
}
});
}
else {throw new Error(
else {
throw new Error(
"onCollide() requires either a function or a tag",
);}
);
}
},

onCollideUpdate(
Expand All @@ -426,9 +439,11 @@ export function area(opt: AreaCompOpt = {}): AreaComp {
(obj, col) => obj.is(tag) && cb?.(obj, col),
);
}
else {throw new Error(
else {
throw new Error(
"onCollideUpdate() requires either a function or a tag",
);}
);
}
},

onCollideEnd(
Expand All @@ -445,9 +460,11 @@ export function area(opt: AreaCompOpt = {}): AreaComp {
(obj) => obj.is(tag) && cb?.(obj),
);
}
else {throw new Error(
else {
throw new Error(
"onCollideEnd() requires either a function or a tag",
);}
);
}
},

hasPoint(pt: Vec2): boolean {
Expand Down Expand Up @@ -517,9 +534,11 @@ export function area(opt: AreaCompOpt = {}): AreaComp {
if (this.area.scale.x == this.area.scale.y) {
return `area: ${this.area.scale.x.toFixed(1)}x`;
}
else {return `area: (${this.area.scale.x.toFixed(1)}x, ${
else {
return `area: (${this.area.scale.x.toFixed(1)}x, ${
this.area.scale.y.toFixed(1)
}y)`;}
}y)`;
}
},
};
}
5 changes: 5 additions & 0 deletions src/kaplay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ import {
textInput,
tile,
timer,
usesArea,
uvquad,
z,
} from "./components";
Expand Down Expand Up @@ -743,6 +744,10 @@ const kaplay = <
}

function checkFrame() {
if (!usesArea()) {
return;
}

// TODO: persistent grid?
// start a spatial hash grid for more efficient collision detection
const grid: Record<number, Record<number, GameObj<AreaComp>[]>> = {};
Expand Down

0 comments on commit 15e9992

Please sign in to comment.