top-down-action-adventure/src/message.js

65 lines
1.8 KiB
JavaScript
Raw Normal View History

2025-06-07 09:28:18 -04:00
export default class Message {
constructor(game, text) {
this.game = game
2025-06-07 09:55:54 -04:00
this.text = text.split("\n")
this.currentText = this.text.shift()
2025-06-07 09:28:18 -04:00
this.textColor = "white"
this.backgroundColor = "black"
this.textIndex = 0
this.textProgress = 0.0
this.textSpeed = 0.08 // seconds per character
this.backgroundHeight = 40
this.textSize = 30
}
tick(dt) {
this.textProgress += (dt / 1000.0) / this.textSpeed
this.textIndex = Math.floor(this.textProgress)
const ijp = this.game.input.isInputJustPressed("interact")
if (ijp) {
if (this.messageComplete()) {
this.game.closeMessage(this)
2025-06-07 09:55:54 -04:00
} else if (this.lineComplete()) {
this.currentText = this.text.shift()
this.textProgress = 0.0
this.textIndex = 0
2025-06-07 09:28:18 -04:00
} else {
2025-06-07 09:55:54 -04:00
this.textProgress = this.currentText.length
2025-06-07 09:28:18 -04:00
}
}
}
draw(ctx) {
ctx.fillStyle = this.backgroundColor
ctx.fillRect(0, 0, ctx.canvas.width, this.backgroundHeight)
ctx.font = `bold ${this.textSize}px sans-serif`
ctx.textBaseline = "top"
ctx.fillStyle = this.textColor
2025-06-07 09:55:54 -04:00
ctx.fillText(this.currentText.substring(0, this.textIndex), 5, 5)
2025-06-07 09:28:18 -04:00
if (this.messageComplete()) {
ctx.fillRect(
ctx.canvas.width - 20,
this.backgroundHeight - 20,
10, 10
)
2025-06-07 09:55:54 -04:00
} else if (this.lineComplete()) {
ctx.beginPath()
ctx.moveTo(ctx.canvas.width - 20, this.backgroundHeight - 20)
ctx.lineTo(ctx.canvas.width - 20, this.backgroundHeight - 10)
ctx.lineTo(ctx.canvas.width - 15, this.backgroundHeight - 15)
ctx.lineTo(ctx.canvas.width - 20, this.backgroundHeight - 20)
ctx.fill()
ctx.closePath()
2025-06-07 09:28:18 -04:00
}
}
2025-06-07 09:55:54 -04:00
lineComplete() {
return this.textIndex >= this.currentText.length + 3
}
2025-06-07 09:28:18 -04:00
messageComplete() {
2025-06-07 09:55:54 -04:00
return this.lineComplete() && !this.text.length
2025-06-07 09:28:18 -04:00
}
}