我正在编写一个实时游戏,但我不知道如何实时移动(如 mmorpg 游戏)
现在我的代码只向窗口添加新字符..
看看,请告诉我任何建议!:(
服务器(Socket.io):
var handler = function(req, res) {
fs.readFile('./index.html', function (err, data) {
if(err) throw err;
res.writeHead(200);
res.end(data);
});
}
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var port = 3250;
app.listen(port);
var postacie = [];
var idGenerator = 0;
// socket.io
io.sockets.on('connection', function (socket) {
var pId = idGenerator++;
socket.emit("list", postacie);
var postac = createChar(pId);
postacie.push(postac);
io.sockets.emit("join", postac);
socket.on("disconnect", function()
{
var sId = "character" + pId;
for (var i = 0,n=postacie.length; i < n; ++i) {
var postac = postacie[i];
if (postac.id == sId) {
io.sockets.emit("leave", {id:postac.id});
postacie.splice(i, 1);
break;
}
}
});
});
function createChar(id)
{
var postac = {
src: "http://img703.imageshack.us/img703/1416/2st.gif",
id: "character" + id
};
return postac;
}
客户:
<!DOCTYPE html>
<html>
<head>
<title>Real tie game</title>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
window.onload = function() {
var socket = io.connect('http://localhost:3250');
socket.on("join", function(data)
{
var element = document.createElement('img');
element.src = data.src;
element.id = data.id;
var body = document.getElementsByTagName('body')[0];
body.appendChild(element);
});
socket.on("list", function(data)
{
for (var i=0; i < data.length; i++) {
var element = document.createElement('img');
element.src = data[i].src;
element.id = data[i].id;
var body = document.getElementsByTagName('body')[0];
body.appendChild(element);
};
});
socket.on("leave", function(data)
{
var element = document.getElementById(data.id);
if (element)
element.parentNode.removeChild(element);
});
}
</script>
</head>
<body>
</body>
</html>