Phaser.js中基于速度的坠落伤害变量fallDmgAmt莫名重置问题排查
坠落伤害计算问题排查与修复
核心问题分析
你的代码里有几个关键问题导致fallDmgAmt莫名重置为0:
- 全局强制重置:代码第一行
this.gameState.fallDmgAmt = 0;会在这段逻辑的每次执行(通常是每帧)都强制把伤害值清零,哪怕后面刚计算出对应速度的伤害量,下一次帧运行时又会被重置,落地时自然拿到的是0。 - 语法错误:两处
this}是无效语法,应该改为},这会导致代码执行异常、逻辑中断。 - 冗余的独立if判断:多个速度判断是独立的
if而非else if,虽然最终会取最大速度对应的伤害值,但会产生不必要的重复赋值,降低效率。
修复方案
- 移除全局的
this.gameState.fallDmgAmt = 0;,只在落地处理完成后或开始新坠落前重置伤害值。 - 修复语法错误,把
this}改为}。 - 将独立
if改为else if,确保每个速度区间只执行一次赋值。 - 调整坠落触发逻辑,避免不必要的
return打断后续计算。
修复后的代码示例
// fall damage if ( !this.player.body.onFloor() && this.player.body.velocity.y >= 250 && !this.falling ) { this.falling = true; this.currentFalling = true; // 开始坠落后初始化伤害值,避免残留旧值 this.gameState.fallDmgAmt = 0; } if (this.falling && !this.flying && this.player.body.velocity.y >= 1) { if (this.player.body.velocity.y >= 850) { this.gameState.fallDmgAmt = 10; } else if (this.player.body.velocity.y >= 750) { this.gameState.fallDmgAmt = 8; } else if (this.player.body.velocity.y >= 650) { this.gameState.fallDmgAmt = 6; } else if (this.player.body.velocity.y >= 550) { this.gameState.fallDmgAmt = 5; } else if (this.player.body.velocity.y >= 450) { this.gameState.fallDmgAmt = 4; } else if (this.player.body.velocity.y >= 350) { this.gameState.fallDmgAmt = 2; } else if (this.player.body.velocity.y >= 250) { this.gameState.fallDmgAmt = 1; } console.log(this.gameState.fallDmgAmt); } if (this.player.body.onFloor() && this.falling && !this.flying) { console.log(this.gameState.fallDmgAmt); this.health -= this.gameState.fallDmgAmt; if (this.health <= 0) { this.health = 0; this.scene.launch("death"); this.health = 10; this.changeHealth(this.health); this.scene.pause(); } this.changeHealth(this.health); this.falling = false; // 落地后重置伤害值,准备下一次坠落计算 this.gameState.fallDmgAmt = 0; }
额外说明
- 把速度判断从高到低排列,这样只要满足高阈值就不会进入低阈值判断,逻辑更高效。
- 移除了不必要的
return,确保每帧都能执行完整的坠落伤害计算逻辑。
内容的提问来源于stack exchange,提问作者Vatsa Pandey
相关产品推荐
相关产品推荐

