JSFiddle - React, Tailwind, and code Playground

by CrazyDave2345

JavaScript

const buffer = [];
const position = [0, 0];
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let last_x = 0

function Packet(info, t) {

	buffer.push(info);
}

function Lerp() {
	if (buffer.length > 0) {
 		const current = buffer[0];
    const distance = Math.sqrt(Math.pow(current[0] - position[0], 2) + Math.pow(current[1] - position[1], 2));
    if (distance > 0) {
      const direction = Math.atan2(current[1] - position[1], current[0] - position[0]);
    	position[0] += ((distance < 10) ? distance : 10) * Math.cos(direction);
      position[1] += ((distance < 10) ? distance : 10) * Math.sin(direction);
    } else {
    	buffer.shift();
    }
  }
}

function GameUpdate() {
	Lerp();
  ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.beginPath();
  ctx.lineWidth = "6";
  ctx.strokeStyle = "red";
  ctx.rect(position[0] + 12.5, position[1] + 12.5, 25, 25);
  ctx.stroke();
  ctx.closePath();
}

function sendPacket(packet, t) {
function randn_bm() {
    var u = 0, v = 0;
    while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)
    while(v === 0) v = Math.random();
    return Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
}
  // unstable connection.
  // The ms is > 100 2.7% of the time, or one update frame every 1.5
  // seconds-- something the algorithm should well be able to handle.
 
  let variance = 20
  let latency = 70 + (randn_bm()*variance)-(variance/2)
  setTimeout(() => Packet(packet, t), latency)

}

// There needs to be a 
//function initializeClient
// the packets 

// todo: a test that runs with two canvases on 2 connections, one good
// and one bad. They should be mirrors of each other.
async function startServer() {
  let syncedTime = 0
  const serverFPS = 25
  sendPacket([100, 100], syncedTime++);
  await delay(1/serverFPS)
  sendPacket([150, 100], syncedTime++);
}

setInterval(GameUpdate, 60);