问题描述
我觉得我做错了什么,但是在寻找与Phaser + Typescript相关的范围问题时,我没有提出任何建议(尽管JS'this'/范围有很多声音-看起来翻译得不太好).
I feel like I'm doing something wrong, but searching for Phaser + Typescript related scope issues I'm coming up with nothing (tons on JS 'this' / scope though - it doesn't seem to translate well).
我正在尝试设置一个Phaser.Game实例,据我所知,该实例需要一些回调(在我的情况下,是预加载,创建然后更新).直到浏览器关闭,更新才会被调用.
I'm trying to set up a Phaser.Game instance, which from my understanding takes a few callbacks (in my case, preload, create then update). Update gets called until the browser is closed.
我的问题是在update中,我无法访问当前类中的变量.
My issue is that inside update, I have no access to the variables inside the current class.
代码:
import { Player } from "./Player";
import { InputManager } from "./input/InputManager";
import { Point } from "./geometry/Point";
export class Game {
private player: Player;
private inputManager: InputManager;
private game: Phaser.Game;
constructor() {
this.player = new Player();
this.inputManager = new InputManager(new Phaser.Keyboard(this.game));
this.game = new Phaser.Game(1024,400, Phaser.AUTO, 'content', { preload: this.preload, create: this.create, update: this.update });
}
private preload(): void {
console.log(this.inputManager); // undefined
this.game.load.image('terminal', 'terminal.png');
}
private create(): void {
console.log("create");
console.log(this.inputManager); // undefined
var logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'terminal');
logo.anchor.setTo(0.5, 0.5);
}
private update(): void {
// update gets called right away, so check for inputManager to be initialized before contuing
if(!this.inputManager) { // Will always be false - "this" isn't what i'm expecting
console.log("undefined iputManager");
return;
}
console.log("initialized update");
this.inputManager.update();
if(this.inputManager.newDirection)
{
this.move(this.inputManager.newDirection);
this.inputManager.Clear();
}
}
private move(newDirection: Point): void {
// TODO: Movement check for the player
this.player.Location.X += newDirection.X;
this.player.Location.Y += newDirection.Y;
}
}
推荐答案
很确定它在此行上:
this.game = new Phaser.Game(1024,400, Phaser.AUTO, 'content', { preload: this.preload, create: this.create, update: this.update });
您尚未将上下文与this.update
关联,因此当Phaser调用它时,它不知道this
应该是什么.
You haven't associated a context with this.update
, so when Phaser calls it, it won't know what this
should be.
尝试执行update: () => this.update()
,update: this.update.bind(this)
甚至update: function() { _this.update() }
(其中_this
是捕获函数外部this
正确值的变量),具体取决于您的JS版本.
Try doing update: () => this.update()
, or update: this.update.bind(this)
, or even update: function() { _this.update() }
(where _this
is a variable that captured the correct value of this
outside of the function), depending on your version of JS.
这篇关于移相器+打字稿在更新中丢失了范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!