[英]socket.io emit returns the same value
Quick question here can someone tell me why everytime I emit from client attack
the enemyHealth
and userHealth
always stays at 94 every emit and it's not decreasing by 6 on every attack emit ? 这里有一个
enemyHealth
问题,有人可以告诉我,为什么我每次从客户端attack
发射时, enemyHealth
和userHealth
每次发射始终保持94,而不是每次攻击时减少6? It only decreases on first click. 仅在首次点击时减少。
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);
});
The reason enemyHealth
and userHealth
remain the same on each attack
event is that those variables are being declared in the attack
event itself, meaining their value will always be the same each time the attack
event occurs. 每个
attack
事件上的enemyHealth
和userHealth
保持相同的原因是,这些变量是在attack
事件本身中声明的,因此,每次attack
事件发生时,它们的值将始终相同。
One way to resolve your issue is to simply move the declaration and initialisation of enemyHealth
and userHealth
outside of your attack
event handler like so: 解决您的问题的一种方法是,只需简单地将
enemyHealth
和用户userHealth
的声明和初始化enemyHealth
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.