gpt4 book ai didi

typescript - TypeScript 中基于组件的架构

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:20 26 4
gpt4 key购买 nike

我正在使用 Phaser 和 TypeScript 制作游戏。我想为 Actors 实现一个基于组件的架构。我想要实现的是这样的:

var component:AwesomeComponent = actor.getComponent<AwesomeComponent>();

我知道有一个 workaround通过构造 T 类型的对象。但我不喜欢它,因为我可能需要定义大量不同的构造函数来表示所有不同类型的组件。

我目前所做的是传递一个带有类型的字符串(当然数字会更好,但我仍在制作原型(prototype)):

getComponent<T>(componentType:string): T 
{
for (let i = 0; i < this.components.length; i++)
{
if (componentType == this.components[i].componentType)
{
return <T><any>this.components[i];
}
}
return undefined;
}

可以,但是效果不好,必须输入两次类名:

var animComp = actor.getComponent<AnimationComponent>("AnimationComponent");

有什么解决办法吗?

感谢您的宝贵时间!

最佳答案

我在 Phaser 论坛上得到了一些很好的建议,用户@flyovergames 显示的解决方案正是我要找的:

<script src="https://raw.githubusercontent.com/photonstorm/phaser/master/v2/src/Phaser.js"></script>
class Component {
public actor: Actor;
}

interface ComponentType<T extends Component> { new(...args: any[]): T }

class Actor {
public components: Component[] = [];

private getComponentIndex<T extends Component>(type: ComponentType<T>): number {
for (let i = 0; i < this.components.length; ++i) {
const component: Component = this.components[i];
if (component instanceof type) {
return i;
}
}
return -1;
}

public hasComponent<T extends Component>(type: ComponentType<T>): boolean {
return this.getComponentIndex(type) !== -1;
}

public getComponent<T extends Component>(type: ComponentType<T>, ...args: any[]): T {
const index: number = this.getComponentIndex(type);
if (index !== -1) {
return this.components[index] as T;
}
return this.addComponent(type, ...args);
}

public addComponent<T extends Component>(type: ComponentType<T>, ...args: any[]): T {
if (this.hasComponent(type)) { return this.getComponent(type); }
const component: T = new type(...args); // this needs ES5
component.actor = this;
this.components.push(component);
return component;
}

public delComponent<T extends Component>(type: ComponentType<T>): T {
const component: Component = this.getComponent(type);
this.components.splice(this.components.indexOf(component), 1);
component.actor = undefined;
return component as T;
}
}

class AwesomeComponent extends Component {
public message: string;
constructor(message: string) {
super();
this.message = message;
}
public alert(): void {
console.log(this.message);
}
}

function test(): void {
const actor: Actor = new Actor();
if (actor.hasComponent(AwesomeComponent)) { throw new Error(); }
actor.addComponent(AwesomeComponent, "awesome!");
const awesome: AwesomeComponent = actor.getComponent(AwesomeComponent); // automatic cast!
awesome.alert();
actor.delComponent(AwesomeComponent);
if (actor.hasComponent(AwesomeComponent)) { throw new Error(); }
}

test();

全文链接: Solution

关于typescript - TypeScript 中基于组件的架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44760189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com