简体   繁体   English

如何在Phaser中正确使用Typescript扩展类

[英]How to correctly use Typescript extended classes with Phaser

I am new to both Javascript and Typescript. 我是Javascript和Typescript的新手。 I've written a simple Phaser game in Javascript and now want to re-write it in Typescript ES2015 (ES6). 我已经用Javascript编写了一个简单的Phaser游戏,现在想在Typescript ES2015(ES6)中重新编写它。
I have extended the Phaser.Game class such that it is passed a variable through it's constructor. 我扩展了Phaser.Game类,以便通过其构造函数传递变量。 This is used to create a websocket. 这用于创建WebSocket。 This socket could exist as a property of the Game or State types (I show this in the example). 此套接字可以作为Game或State类型的属性存在(在示例中显示)。
I've extended the Phaser.State class to include the property that needs to be set by the websocket data through the websocket's .onmessage member function. 我扩展了Phaser.State类,使其包含需要通过websocket的.onmessage成员函数由websocket数据设置的属性。

I've shown the createWebsocket as a function just for completeness, in reality it's a member function of one of the classes. 我已经将createWebsocket展示为一个功能,只是为了完整性,实际上,它是其中一个类的成员函数。

function createWebsocket(wsPath, callback){
    var ws = new WebSocket(wxPath);
    ws.onmessage = callback;
    return ws;
}

export class Game extends Phaser.Game {
    csocket: WebSocket;
    constructor(wsPath, container) {
    this.state.add('Boot', Boot, false);
    this.csocket = createWebsocket(wsPath, this.handleMsg);
}

export class Boot extends Phaser.State {
    csocket: WebSocket;
    constructor(){super();}
    my_value: number;
    setMyValue(value) {this.my_value = value};
    this.csocket = createWebsocket(wsPath, this.handleMsg);
}

How do I either pass data from the extended Game class instance to the Boot instance or access the createWebsocket member function of the Boot instance? 如何将数据从扩展的Game类实例传递到Boot实例,或者如何访问Boot实例的createWebsocket成员函数?

If I use the following in Game; 如果我在游戏中使用以下内容;

state = this.state.getCurrentState();
state.setValue()

I get a (trans)compiler error as getCurrentState() returns the instance of the base class not the extended class even though the extended class type is passed to the state.add function 我收到一个(trans)编译器错误,因为即使扩展类类型被传递给state.getCurrentState()返回基类的实例而不是扩展类的实例。

I see no way to pass the wsPath to the constructor for the Boot class as a type is passed to the .add function. 我看不到将wsPath传递给Boot类的构造函数的方法,因为类型已传递给.add函数。

The simple answers are always the best ones. 简单的答案永远是最好的答案。 So, answering my own question...... 所以,回答我自己的问题……

Though the examples don't clearly show this, the this.state.add call does not just allow a class, it also allows a class instance. 尽管示例中并未明确显示这一点,但是this.state.add调用不仅允许类,还允许类实例。 Just use new. 只需使用new。

export class Game extends Phaser.Game {
    csocket: WebSocket;
    constructor(wsPath, container) {
        var bootState = new Boot(wsPath);
        this.state.add('Boot', bootState, false);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM