我试图在打字稿中实现实体组件系统模式。我有一个实体类,我想在其中保留实体的组件。我想为这个模式创建独立的包并在我的其他项目中使用它。
这是我有错误的实体类。
type IComponents<N> = {
[P in keyof N]?: Component<any, N>;
}
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface EntityType<N> {
id: string;
components: IComponents<N>;
addComponent(component: Component<any, N>): void;
removeComponent(componentId: N): void;
print(): void;
}
export default class Entity<N> implements EntityType<N> {
readonly id: string;
components: IComponents<N> = {};
constructor() {
this.id = v4();
}
addComponent(component: Component<any, N>): void {
this.components[component.name] = component;
}
removeComponent(componentName: N): void {
delete this.components[componentName];
}
print(): void {
console.log(JSON.stringify(this, null, 4));
}
}
在方法中addComponents
我得到了这个错误
Type 'N' cannot be used to index type 'IComponents<N>'.
这是Component
班级的签名
export default abstract class Component<P, N> {
readonly id: string;
readonly name: N;
props: P;
protected constructor(props: P, name: N) {
this.props = props;
this.name = name;
this.id = v4();
}
}
有一个项目我使用这个包:
为组件创建组件、实体和枚举
export enum EComponents {
position,
}
export default (): Entity<EComponents> => {
const player = new Entity<EComponents>();
player.addComponent(new PositionComponent());
return player;
};
获取实体并处理它的系统。在这种方法中,我想从entity.components
特定组件中获取并处理它
update(entity: Entity): void {
const component: PositionComponent | null = this.getComponent(entity);
if (!component) return;
const { x = 0, y = 0 } = component.props;
const position = { x, y };
if (this.keyboard.isKeyPressed('KeyW')) {
position.y -= 3;
}
if (this.keyboard.isKeyPressed('KeyA')) {
position.x -= 3;
}
if (this.keyboard.isKeyPressed('KeyS')) {
position.y += 3;
}
if (this.keyboard.isKeyPressed('KeyD')) {
position.x += 3;
}
entity.components['Position'].props = position;
}