Integers and Strings in JavaScript

Joe and I just spent an hour or so debugging my Node.js application, a simple multiplayer tag game. The problem was that while a player was moving, they disappeared from every other player’s view. Not the greatest for playability.

So we dove in to the code, and figured out that on each loop, the x and y of each player object looked something like this (x,y):

(299, 445)

then

(2991.3423, 445)

then

(2991.34231.3423, 445)

etc.

So, each time the main game went along, “1.3423” got appended to the x and y variables. We were adding the velocityX and velocityY components to the x and y respectively, so they were somehow getting concatenated instead of added.

It turns out I was doing the following:

Client:

GET(
    'loop/' + currentPlayer.id + "/" + currentPlayer.x + "/" + currentPlayer.y + "/" + currentPlayer.vx + "/" + currentPlayer.vy + "/" + currentPlayer.keyx + "/" + currentPlayer.keyy, function(data){
    hasReturned = true;
    updateData = JSON.parse(data);
});

Server:

requrl = req.url.split('/');
requrl.shift();
currentPlayer.updateLocation(currentWorld, requrl[2], requrl[3], requrl[4], requrl[5], requrl[6], requrl[7]); //world, x, y, vx, vy, keyx, keyy

The problem with this is that each of the variables come back as strings, not integers. So when we call the updateLocation method, we’re passing in strings. Observe:

"1" + "1" // "11"
1 + "1" // "11"
"1" - "1" // 0
"30" * 1 //30
parseFloat("1.234") + 3 // 4.234

So: remember that your URL variables in node are going to come in as strings and not ints or floats, and that if you try to add them to anything, it’ll end up as a concatenation operation.

Hope this saves someone some time someday.

From Manhattan,
— Erty

Leave a Reply

Your email address will not be published.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.