简体   繁体   中英

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 ? 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.

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:

// 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);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM