Problem code multiplayer game NodeJS

3

Hello, I'm having trouble creating a real-time game with node.js, below is the part of the client:

var position = {x:0, y:0};
var canvas = document.querySelector("canvas");
var context = canvas.getContext("2d");
var ws = io.connect("http://localhost:9090");

var keyboard = new Keys();

update();

function draw(position) {
    context.fillRect(position.x, position.y, 50, 50);
}

function update() { 
    window.requestAnimationFrame(update, canvas);
    ws.emit("userMove", position);
    ws.on("serverUserPosition", draw);
}

And here's the part of the server:

var socket = require("socket.io").listen(9090);
socket.sockets.on("connection", run);

function run(user) {
    user.on("userMove", send);
}

function send(position) {
    socket.sockets.emit("serverUserPosition", position);
}

This code does the following, writes a rectangle on the screen every time a user logs in and updates their position according to the user's movements. The problem is that the entire path of the rectangles on the screen is recorded and when using context.clearRect(0, 0, canvas.width, canvas.height); it erases everything

    
asked by anonymous 12.12.2015 / 03:29

1 answer

0

When you use clearRect (0,0, width, heigth) you delete ALL of your canvas. This is because the size of the rectangle you are erasing is the same as the size of your canvas. I did not quite understand your question, but come on:

  • If you want to keep all the history of rectangles on the screen, you do not need to use clearRect. In that case you will not delete any of them.
  • If you want to delete only one rectangle, you should use clearRect (position.x, position.y, 50, 50). This will erase the current rectangle. In case you want to delete the previous rectangle, you only have to use an intermediate variable to store the values of x and y above.
  • 14.12.2015 / 01:01