Skip to content

Instantly share code, notes, and snippets.

@trymnilsen
Created November 17, 2024 15:42
Show Gist options
  • Save trymnilsen/7cb029de15b51602cee5576bdc3c7d47 to your computer and use it in GitHub Desktop.
Save trymnilsen/7cb029de15b51602cee5576bdc3c7d47 to your computer and use it in GitHub Desktop.
Typescript ECS System
export type ComponentFn<T extends EcsComponent = EcsComponent> = new (
...args: any[]
) => T;
export type QueryData<T extends QueryObject = QueryObject> = {
[P in keyof T]: InstanceType<T[P]>[];
};
export interface QueryObject<T extends ComponentFn = ComponentFn> {
[componentName: string]: T;
}
type UpdateFunction<T extends QueryObject> = (
components: QueryData<T>,
gameTime: number,
) => void;
abstract class EcsComponent {}
export class EcsSystem<T extends QueryObject = QueryObject> {
private onUpdate: UpdateFunction<T> | null = null;
constructor(public query: Readonly<T>) {}
runUpdate(components: QueryData<T>, gameTime: number) {
if (this.onUpdate) {
this.onUpdate(components, gameTime);
}
}
withUpdate(updateFunction: UpdateFunction<T>): void {
this.onUpdate = updateFunction;
}
}
class CounterComponent extends EcsComponent {
currentValue: number = 0;
}
const counterSystem = new EcsSystem({
counter: CounterComponent,
});
counterSystem.withUpdate(({counter}) => {
counter[0].currentValue += 42;
console.log("Amount during update", counter[0].currentValue);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment