这里有一个简短的问题,有人可以告诉我为什么我每次从客户端attack
发出enemyHealth
和userHealth
时,每次发出总是保持94,而在每次攻击发出时都不会减少6吗?只会在首次点击时减少。
socket.on('attack', () => {
var userDamage = 6;
var enemyDamage = 6;
var userHealth = 100;
var enemyHealth = 100;
var userDmg = userDamage;
var enemyDmg = enemyDamage;
userHealth -= enemyDmg;
enemyHealth -= userDmg;
console.log(enemyHealth);
});
答案 0 :(得分:0)
在每个enemyHealth
事件中userHealth
和attack
保持相同的原因是,这些变量是在attack
事件本身中声明的,因此它们的值始终为每次attack
事件发生时都是相同的。
解决问题的一种方法是,将enemyHealth
和userHealth
的声明和初始化简单地移到attack
事件处理程序之外,如下所示:
// Declare these variables outside of the attach handler so that their updated
// values are retained between attack events
var userHealth = 100;
var enemyHealth = 100;
socket.on('attack', () => {
var userDamage = 6;
var enemyDamage = 6;
// Remove the variable declarations from inside the attack event
// var userHealth = 100;
// var enemyHealth = 100;
var userDmg = userDamage;
var enemyDmg = enemyDamage;
userHealth -= enemyDmg;
enemyHealth -= userDmg;
// Now this value goes down each time the attach event occours
console.log(enemyHealth);
});