1 decade ago by Joncom
I'm using socket.io to allow players in my game see each other walk around. I currently have things set up so that when players join the game (depending what their username is) a particular "start position" is given to them. And that is where they start in the map.
The problem is this: so far I've had to input those positions into the database myself. I want the game to periodically save the players positions back into the database. I have a PHP file already coded and on standby for just the task. It can update the database simply by access it like so:
My question is: how can I call this URL from my socket server, because it's not a browser, right? So AJAX doesn't really work the same, does it?
In any case, I tried to do AJAX regardless. Here's the a snippet from server.js, my socket application:
If anybody has experience with sockets and synchronizing the information that they have into a database, help! :)
PS - Please excuse the typos if any... it's late.
The problem is this: so far I've had to input those positions into the database myself. I want the game to periodically save the players positions back into the database. I have a PHP file already coded and on standby for just the task. It can update the database simply by access it like so:
update.php?user=joncom&x=16&y=64&facing=left
My question is: how can I call this URL from my socket server, because it's not a browser, right? So AJAX doesn't really work the same, does it?
In any case, I tried to do AJAX regardless. Here's the a snippet from server.js, my socket application:
socket.on('receiveMove', function (currX, currY, direction, client) { socket.broadcast.emit('moveOtherPlayer', currX, currY, direction, client); for(var i in players) { if(players[i].name==client) { var newX = currX; var newY = currY; switch(direction) { case 'left': newX = currX - 16; // !! magic numbers, not cool !! break; case 'right': newX = currX + 16; // !! magic numbers, not cool !! break; case 'up': newY = currY - 16; // !! magic numbers, not cool !! break; case 'down': newY = currY + 16; // !! magic numbers, not cool !! break; }; players[i].pos.x = newX; players[i].pos.y = newY; players[i].facing = direction; // update positions on database var url = "update.php?user=" + client + "&x=" + newX + "&y=" + newY + "&facing=" + direction; var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("myDiv").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", url, true); xmlhttp.send(); break; // no need to search for other players with same name } } });
If anybody has experience with sockets and synchronizing the information that they have into a database, help! :)
PS - Please excuse the typos if any... it's late.