Friday 28 August 2020

How do I create multiple player instances with Socket.io?

I am creating a simple socket.io application that broadcasts everyone in the rooms mouse coordinates to each other which is represented by a circle. Currently it works but only for two players. If a third player joins it takes over the most recently not used circle.​Here is my client side code so far:var socket = io(); var canvas = document.getElementsByClassName("arena")[0]; var ctx = canvas.getContext("2d"); var opps = new Array(); //All the properties of the canvas canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx.fillStyle = "white"; ctx.fillRect(0, 0, canvas.width, canvas.height); /* Gets mouse position and them emit it to server */ var mousePosX = 1; var mousePosY = 1; var radius = 10; function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top, }; } canvas.addEventListener( "mousemove", function (evt) { let mousePos = getMousePos(canvas, evt); ctx.beginPath(); ctx.clearRect( mousePosX - radius - 1, mousePosY - radius - 1, radius * 2 + 2, radius * 2 + 2 ); ctx.closePath(); mousePosX = mousePos.x; mousePosY = mousePos.y; ctx.arc(mousePosX, mousePosY, radius, 0, 2 * Math.PI, false); ctx.fillStyle = "black"; ctx.fill(); socket.emit("pos", { mousePosX, mousePosY, radius, }); }, false ); socket.on("connection", () => console.log("connected")); //Draws other players var previousX = 1; var previousY = 1; socket.on("pos", drawPlayers); function drawPlayers(data) { ctx.beginPath(); ctx.clearRect( previousX - data.radius - 1, previousY - data.radius - 1, data.radius * 2 + 2, data.radius * 2 + 2 ); ctx.closePath(); previousX = data.mousePosX; previousY = data.mousePosY; ctx.arc(data.mousePosX, data.mousePosY, data.radius, 0, 2 * Math.PI, false); ctx.fillStyle = "black"; ctx.fill(); } Towards the bottom I have my function that will draw other players. For the client it draws its circle and then emits its location to everyone else whenever its position changes. The drawPlayers method receives that data on position changes and draws them. What I want it to do is only update the position of the player that is moving and give them their own representative circle.​​EDIT: Also while thinking through this, would including some sort of id when I send the "pos" data and then updating the data before sending it back on server side be a solution?

Submitted August 28, 2020 at 04:36PM by TheSlothJesus

No comments:

Post a Comment