Problem Code Nodejs multiplayer game

Asked

Viewed 139 times

3

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

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 server part:

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 enters and updates its 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 the context.clearRect(0, 0, canvas.width, canvas.height); he erases everything

  • I do not understand. At first, what its function draw should do is draw the screen entire every frame of animation (or at least every frame that something has changed). That is, first she "erases everything" and then she draws everything that has to be drawn. Or did I misinterpret your question?

1 answer

0

When Voce uses clearRect(0.0, width, heigth), Voce erases ALL of your canvas. This is because the dimension of the rectangle that Voce is erasing is equal to the dimension of your canvas. I don’t quite understand your question, but come on:

  1. 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.
  2. 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, just use an intermediate variable to store the previous x and y values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.