gpt4 book ai didi

javascript - socket.io发出返回相同的值

转载 作者:行者123 更新时间:2023-12-03 12:08:20 25 4
gpt4 key购买 nike

这里有一个简短的问题,有人可以告诉我为什么我每次从客户端attack发出时enemyHealthuserHealth每次发出时始终保持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);

});

最佳答案

每个enemyHealth事件上的userHealthattack保持相同的原因是,这些变量是在attack事件本身中声明的,因此每次attack事件发生时,它们的值将始终相同。

解决问题的一种方法是,将enemyHealthuserHealth的声明和初始化简单地移到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);

});

关于javascript - socket.io发出返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52806210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com