我刚开始使用Javascript,第二天就开始了,但我遇到了一个小问题。我正在使用Phaser API并且我正在使用状态,基本上我的问题在于:
game.input.keyboard.addCallbacks(this, null, null, this.keyPress);
我在下面的代码处于相同的状态
keyPress: function(char) {
console.log("pressed");
if(this.selected == 1) {
this.userFieldText.text += char;
} else if(this.selected == 2) {
this.passFieldText.text += char;
}
}
控制台中没有错误,但从不调用该方法。
文档here
var loginButton;
var userField;
var userFieldText;
var passField;
var passFieldText;
var selected;
var stateLogin = {
preload: function() {
game.stage.backgroundColor = '#000';
game.load.image('text-field', 'assets/ui/text-box.png');
game.load.image('login-button', 'assets/ui/login-button.png');
},
create: function() {
this.selected = 0;
var userLabel = game.add.text(200, 200, 'Enter a username: ');
userLabel.fontSize = 20;
userLabel.fill='#fff';
var passLabel = game.add.text(200, 250, 'Enter a password: ');
passLabel.fontSize = 20;
passLabel.fill='#fff';
var userField = game.add.sprite(350, 195, 'text-field');
userField.inputEnabled = true;
userField.events.onInputUp.add(function() { this.selectField('user') }, this);
var passField = game.add.sprite(350, 245, 'text-field');
passField.inputEnabled = true;
passField.events.onInputUp.add(function() { this.selectField('pass') }, this);
this.userFieldText = game.add.text(360, 200, '');
this.userFieldText.fontSize = 16;
this.userFieldText.fill = "#fff";
this.passFieldText = game.add.text(360, 250, '');
this.passFieldText.fontSize = 16;
this.passFieldText.fill = "#fff";
game.input.keyboard.addCallbacks(this, null, null, this.keyPress);
},
update: function() {
console.log('Selected: ' + this.selected + ' Text: ' + this.userFieldText.text);
},
selectField: function(field) {
if(field == 'user') {
this.selected = 1;
} else if(field == 'pass') {
this.selected = 2;
}
},
keyPress: function(char) {
console.log("pressed");
if(this.selected == 1) {
this.userFieldText.text += char;
} else if(this.selected == 2) {
this.passFieldText.text += char;
}
}
};