I' ve got a text displayed in PhaserJS 3 game, then the method onEvent runs on loop adding new text to the current text, it works until it finds '\n', but it gives no error at all.
function create() {
this.savedText = this.add.text(0, 100, "Starting text display")
this.newText = "This text should be displayed \n in two lines"
this.index = 0
this.timedEvent = this.time.addEvent({ delay: 100, callback: this.onEvent, callbackScope: this, loop: true })
}
onEvent() {
let textDisplayed = ""
if(this.index < parseInt(this.newText.length)) {
textDisplayed += this.newText.charAt(this.index)
this.savedText.text += textDisplayed
this.index++
}
}
How can I fix this? Any hints? Thanks in advance.
If the code you have posten, in your question, is 100% the same as in your application, you just missed the keyword function
before onEvent()
. Because your code seems to basically work:
Here a working Demo:
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
scene: {
create
},
};
function create() {
// I added some dots and newlines, at the end just for optical reasons
this.savedText = this.add.text(20, 50, "Starting text display ...\n\n")
this.newText = "This text should be displayed \n in two lines"
this.index = 0
this.timedEvent = this.time.addEvent({ delay: 100, callback: onEvent, callbackScope: this, loop: true })
}
// here you missed the keyword `function`
function onEvent() {
let textDisplayed = ""
if(this.index < parseInt(this.newText.length)) {
textDisplayed += this.newText.charAt(this.index)
this.savedText.text += textDisplayed
this.index++
}
}
new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>
Tipp: for future debugging and posting questions, check the Browser console and the Error message found there since this helps find the problem faster.