2020-04-26 17:54:56 +02:00
|
|
|
|
2020-05-01 23:19:51 +02:00
|
|
|
export class TextInput extends Phaser.GameObjects.BitmapText {
|
2020-10-15 12:05:40 +02:00
|
|
|
private minUnderLineLength = 4;
|
2020-04-26 18:48:41 +02:00
|
|
|
private underLine: Phaser.GameObjects.Text;
|
2020-05-26 22:17:00 +02:00
|
|
|
|
|
|
|
constructor(scene: Phaser.Scene, x: number, y: number, maxLength: number, text: string, onChange: (text: string) => void) {
|
|
|
|
super(scene, x, y, 'main_font', text, 32);
|
2020-10-15 12:05:40 +02:00
|
|
|
this.setOrigin(0.5).setCenterAlign()
|
2020-04-26 17:54:56 +02:00
|
|
|
this.scene.add.existing(this);
|
|
|
|
|
2020-10-15 12:05:40 +02:00
|
|
|
this.underLine = this.scene.add.text(x, y+1, this.getUnderLineBody(text.length), { fontFamily: 'Arial', fontSize: "32px", color: '#ffffff'})
|
|
|
|
this.underLine.setOrigin(0.5)
|
2020-05-01 23:19:51 +02:00
|
|
|
|
2020-04-26 18:48:41 +02:00
|
|
|
|
2020-06-19 16:36:40 +02:00
|
|
|
this.scene.input.keyboard.on('keydown', (event: KeyboardEvent) => {
|
2020-04-26 17:54:56 +02:00
|
|
|
if (event.keyCode === 8 && this.text.length > 0) {
|
2020-04-26 18:48:41 +02:00
|
|
|
this.deleteLetter();
|
2020-05-01 23:19:51 +02:00
|
|
|
} else if ((event.keyCode === 32 || (event.keyCode >= 48 && event.keyCode <= 90)) && this.text.length < maxLength) {
|
2020-04-26 18:48:41 +02:00
|
|
|
this.addLetter(event.key);
|
2020-04-26 17:54:56 +02:00
|
|
|
}
|
2020-10-15 12:05:40 +02:00
|
|
|
this.underLine.text = this.getUnderLineBody(this.text.length);
|
2020-05-26 22:17:00 +02:00
|
|
|
onChange(this.text);
|
2020-04-26 17:54:56 +02:00
|
|
|
});
|
|
|
|
}
|
2020-10-15 12:05:40 +02:00
|
|
|
|
|
|
|
private getUnderLineBody(textLength:number): string {
|
|
|
|
if (textLength < this.minUnderLineLength) textLength = this.minUnderLineLength;
|
|
|
|
let text = '_______';
|
|
|
|
for (let i = this.minUnderLineLength; i < textLength; i++) {
|
|
|
|
text += '__'
|
|
|
|
}
|
|
|
|
return text;
|
|
|
|
}
|
2020-05-01 23:19:51 +02:00
|
|
|
|
2020-04-26 18:48:41 +02:00
|
|
|
private deleteLetter() {
|
|
|
|
this.text = this.text.substr(0, this.text.length - 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private addLetter(letter: string) {
|
|
|
|
this.text += letter;
|
|
|
|
}
|
|
|
|
|
2020-04-26 17:54:56 +02:00
|
|
|
getText(): string {
|
|
|
|
return this.text;
|
|
|
|
}
|
2020-10-07 18:03:34 +02:00
|
|
|
|
|
|
|
setX(x: number): this {
|
|
|
|
super.setX(x);
|
|
|
|
this.underLine.x = x;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
setY(y: number): this {
|
|
|
|
super.setY(y);
|
|
|
|
this.underLine.y = y+1;
|
|
|
|
return this;
|
|
|
|
}
|
2020-05-01 23:19:51 +02:00
|
|
|
}
|