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);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.