游戏终局Boss状态栏百分比更新异常问题求助
问题分析与解决方案
问题根源
- setPercentage调用无参数:在
handleEndbossCollision中调用this.statusBarEndboss.setPercentage();时未传入任何值,导致setPercentage方法内的percentage参数为undefined,直接赋值给this.percentage后引发后续逻辑错误。 - 生命值百分比计算缺失:未根据Boss受击次数(
enemy.hits)计算正确的剩余生命值百分比,无法传递有效的数值更新状态栏。 - resolveImageIndex逻辑错误:原判断条件使用
>而非>=,导致80%、60%等关键数值无法匹配到正确的图片索引(例如80%会被判定为>60,返回索引3对应60%的图片)。
修复步骤
1. 修复状态栏更新调用
在handleEndbossCollision方法中,传入根据受击次数计算的剩余百分比:
// 替换原调用语句 this.statusBarEndboss.setPercentage(100 - enemy.hits * 20);
2. 修正resolveImageIndex的判断逻辑
调整条件为>=,确保每个百分比区间匹配正确的图片:
resolveImageIndex() { console.log('Current Percentage:', this.percentage); if (this.percentage >= 100) { return 5; } else if (this.percentage >= 80) { return 4; } else if (this.percentage >= 60) { return 3; } else if (this.percentage >= 40) { return 2; } else if (this.percentage >= 20) { return 1; } else { return 0; } }
3. (可选)增强setPercentage的鲁棒性
添加参数默认值,避免因无参数传入导致的undefined问题:
setPercentage(percentage = this.percentage) { this.percentage = percentage; let path = this.IMAGES[this.resolveImageIndex()]; this.img = this.imageCache[path]; }
完整修复后代码示例
StatusbarEndboss类
class StatusbarEndboss extends DrawableObject { IMAGES = [ 'img/7_statusbars/2_statusbar_endboss/0.png', 'img/7_statusbars/2_statusbar_endboss/20.png', 'img/7_statusbars/2_statusbar_endboss/40.png', 'img/7_statusbars/2_statusbar_endboss/60.png', 'img/7_statusbars/2_statusbar_endboss/80.png', 'img/7_statusbars/2_statusbar_endboss/100.png' ]; constructor() { super(); this.loadImages(this.IMAGES); this.x = 40; this.y = 50; this.width = 240; this.height = 80; this.percentage = 100; this.setPercentage(this.percentage); } setPercentage(percentage = this.percentage) { this.percentage = percentage; let path = this.IMAGES[this.resolveImageIndex()]; this.img = this.imageCache[path]; } resolveImageIndex() { console.log('Current Percentage:', this.percentage); if (this.percentage >= 100) { return 5; } else if (this.percentage >= 80) { return 4; } else if (this.percentage >= 60) { return 3; } else if (this.percentage >= 40) { return 2; } else if (this.percentage >= 20) { return 1; } else { return 0; } } }
handleEndbossCollision方法
handleEndbossCollision(enemy) { if (enemy.isCollided) { return; } enemy.hits += 1; if (enemy.hits === 4) { enemy.dead = true; this.character.endboss_dead.play(); enemy.stopMoving(); return; } enemy.isCollided = true; setTimeout(() => { enemy.isCollided = false; }, 1650); if (!enemy.isAlert) { enemy.isAlert = true; } this.character.endboss_hurt.play(); enemy.stopMoving(); enemy.hurt = true; setTimeout(() => { enemy.hurt = false; enemy.resumeMoving(); enemy.speed *= 1.3; }, 1500); // 修复:传入计算后的剩余百分比 this.statusBarEndboss.setPercentage(100 - enemy.hits * 20); }
内容的提问来源于stack exchange,提问作者l0U
相关产品推荐
相关产品推荐

