This commit is contained in:
Schluffe
2026-03-17 23:26:16 +01:00
parent 3242e8cbbb
commit 31ae9d94d5
5 changed files with 51 additions and 36 deletions
+25
View File
@@ -0,0 +1,25 @@
export default class RingBuffer<T> {
size: number;
mask: number;
cursor: number;
buffer: Array<T>;
constructor(size: number, blueprint: T) {
if ((size & (size - 1)) !== 0) {
throw new Error("size must be a power of two");
}
this.size = size;
this.mask = size - 1;
this.cursor = 0;
this.buffer = [];
for (let i = 0; i < size; i++) {
this.buffer.push(structuredClone(blueprint));
}
}
next(): T {
return this.buffer[this.cursor++ & this.mask];
}
}
+19 -29
View File
@@ -1,9 +1,10 @@
import type { Circle } from "#/engine/Circle.ts";
import type MapProxy from "#/engine/lib/MapProxy.ts";
import RingBuffer from "#/engine/lib/RingBuffer.ts";
import type { Polygon } from "#/engine/Polygon.ts";
import type { Rect } from "#/engine/Rect.ts";
import $ from "#/engine/Scene.ts";
import type { Vector } from "#/engine/Vector.ts";
import { createVector, type Vector } from "#/engine/Vector.ts";
const CIRCLE = 0;
const RECT = 1;
@@ -13,49 +14,38 @@ type Shape = 0 | 1 | 2;
export type Collider = {
shape: Shape;
collision: Collision;
};
export type Collision = {
id: string;
};
const collisions = new Map<string, Collision>();
function check(
id: string,
collider: Collider,
position: Vector,
colliders: MapProxy<string, Collider>,
): string | undefined {
for (const [oid, other] of colliders.entries()) {
if (oid !== id && other) {
return oid;
}
}
export function createCollider(shape: Shape): Collider {
return {
shape,
collision: { id: "" },
};
}
const collisions = new RingBuffer(128, {
id: "",
normal: createVector(),
});
export function moveAndCollide(
id: string,
velocity: Vector,
delta: number,
): Collision | undefined {
return collisions.get(id);
}
export function processPhysics(
ctx: CanvasRenderingContext2D,
delta: number,
): void {
const colliders = $<Collider>("collider")!;
const positions = $<Vector>("position")!;
for (const [id, collider] of colliders.entries()) {
const position = positions.get(id)!;
const target = check(id, collider.value, position.value, colliders);
if (target !== undefined) {
collisions.set(id, { id: target });
} else {
collisions.delete(id);
for (const [oid, _] of colliders.entries()) {
if (oid === id) {
continue;
}
const self = colliders.get(id)!.value;
self.collision.id = oid;
}
}