lol cursor is multiplayer now

This commit is contained in:
ari melody 2025-03-14 20:42:44 +00:00
parent a797e82a68
commit 4b3c8f9449
Signed by: ari
GPG key ID: 60B5F0386E3DDB7E
7 changed files with 362 additions and 107 deletions

View file

@ -2,8 +2,9 @@ import config from './config.js';
const CURSOR_TICK_RATE = 1000/30;
const CURSOR_LERP_RATE = 1/100;
const CURSOR_FUNCHAR_RATE = 20;
const CURSOR_CHAR_MAX_LIFE = 5000;
const CURSOR_MAX_CHARS = 50;
const CURSOR_MAX_CHARS = 64;
/** @type HTMLElement */
let cursorContainer;
@ -11,61 +12,57 @@ let cursorContainer;
let myCursor;
/** @type Map<number, Cursor> */
let cursors = new Map();
/** @type Array<FunChar> */
let chars = new Array();
/** @type WebSocket */
let ws;
let running = false;
let lastCursorUpdateTime = 0;
let lastCharUpdateTime = 0;
let lastUpdate = 0;
class Cursor {
/** @type number */ id;
// real coordinates (canonical)
/** @type number */ x;
/** @type number */ y;
// update coordinates (interpolated)
/** @type number */ rx;
/** @type number */ ry;
/** @type HTMLElement */
#element;
/** @type HTMLElement */
#char;
#charElement;
#funCharCooldown = CURSOR_FUNCHAR_RATE;
/**
* @param {number} id
* @param {string} id
* @param {number} x
* @param {number} y
*/
constructor(id, x, y) {
this.id = id;
// real coordinates (canonical)
this.x = x;
this.y = y;
// render coordinates (interpolated)
this.rx = x;
this.ry = y;
this.msg = '';
this.funChars = new Array();
const element = document.createElement('i');
element.classList.add('cursor');
element.id = 'cursor' + id;
const colour = randomColour();
element.style.borderColor = colour;
element.style.color = colour;
element.innerText = '0x' + navigator.userAgent.hashCode();
const char = document.createElement('p');
char.className = 'char';
element.appendChild(char);
cursorContainer.appendChild(element);
this.#element = element;
this.#char = char;
cursorContainer.appendChild(this.#element);
const char = document.createElement('i');
char.className = 'char';
cursorContainer.appendChild(char);
this.#charElement = char;
this.setID(id);
}
destroy() {
this.#element.remove();
this.#char.remove();
this.#charElement.remove();
this.funChars.forEach(char => {
char.destroy();
});
}
/**
@ -85,14 +82,52 @@ class Cursor {
this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime;
this.#element.style.left = this.rx + 'px';
this.#element.style.top = this.ry + 'px';
this.#charElement.style.left = this.rx + 'px';
this.#charElement.style.top = (this.ry - 24) + 'px';
if (this.#funCharCooldown > 0)
this.#funCharCooldown -= deltaTime;
if (this.msg.length > 0) {
if (config.cursorFunMode === true) {
if (this.#funCharCooldown <= 0) {
this.#funCharCooldown = CURSOR_FUNCHAR_RATE;
if (this.funChars.length >= CURSOR_MAX_CHARS) {
const char = this.funChars.shift();
char.destroy();
}
const yOffset = -20;
const accelMultiplier = 0.002;
this.funChars.push(new FunChar(
this.x + window.scrollX, this.y + window.scrollY + yOffset,
(this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier,
this.msg));
}
} else {
this.#charElement.innerText = this.msg;
}
} else {
this.#charElement.innerText = '';
}
this.funChars.forEach(char => {
if (char.life > CURSOR_CHAR_MAX_LIFE ||
char.y > document.body.clientHeight ||
char.x < 0 ||
char.x > document.body.clientWidth
) {
this.funChars = this.funChars.filter(c => c !== this);
char.destroy();
return;
}
char.update(deltaTime);
});
}
/**
* @param {string} text
*/
print(text) {
if (text.length > 1) return;
this.#char.innerText = text;
setID(id) {
this.id = id;
this.#element.id = 'cursor' + id;
this.#element.innerText = '0x' + id.toString(16).slice(0, 8).padStart(8, '0');
}
/**
@ -107,12 +142,6 @@ class Cursor {
}
class FunChar {
/** @type number */ x; y;
/** @type number */ xa; ya;
/** @type number */ r; ra;
/** @type HTMLElement */ element;
/** @type number */ life;
/**
* @param {number} x
* @param {number} y
@ -144,14 +173,6 @@ class FunChar {
*/
update(deltaTime) {
this.life += deltaTime;
if (this.life > CURSOR_CHAR_MAX_LIFE ||
this.y > document.body.clientHeight ||
this.x < 0 ||
this.x > document.body.clientWidth
) {
this.destroy();
return;
}
this.x += this.xa * deltaTime;
this.y += this.ya * deltaTime;
@ -164,22 +185,10 @@ class FunChar {
}
destroy() {
chars = chars.filter(char => char !== this);
this.element.remove();
}
}
String.prototype.hashCode = function() {
var hash = 0;
if (this.length === 0) return hash;
for (let i = 0; i < this.length; i++) {
const chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // convert to 32-bit integer
}
return Math.round(Math.abs(hash)).toString(16).slice(0, 8).padStart(8, '0');
};
/**
* @returns string
*/
@ -198,6 +207,8 @@ function randomColour() {
*/
function handleMouseMove(event) {
if (!myCursor) return;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`pos:${event.x}:${event.y}`);
myCursor.move(event.x, event.y);
}
@ -211,26 +222,19 @@ function handleMouseUp() {
/**
* @param {KeyboardEvent} event
*/
function handleKeyDown(event) {
function handleKeyPress(event) {
if (event.key.length > 1) return;
if (event.metaKey || event.ctrlKey) return;
if (config.cursorFunMode === true) {
const yOffset = -20;
const accelMultiplier = 0.002;
if (chars.length < CURSOR_MAX_CHARS)
chars.push(new FunChar(
myCursor.x + window.scrollX, myCursor.y + window.scrollY + yOffset,
(myCursor.x - myCursor.rx) * accelMultiplier, (myCursor.y - myCursor.ry) * accelMultiplier,
event.key));
} else {
myCursor.print(event.key);
}
if (myCursor.msg === event.key) return;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`char:${event.key}`);
myCursor.msg = event.key;
}
function handleKeyUp() {
if (!config.cursorFunMode) {
myCursor.print('');
}
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`nochar`);
myCursor.msg = '';
}
/**
@ -239,32 +243,16 @@ function handleKeyUp() {
function updateCursors(time) {
if (!running) return;
const deltaTime = time - lastCursorUpdateTime;
const deltaTime = time - lastUpdate;
cursors.forEach(cursor => {
cursor.update(deltaTime);
});
lastCursorUpdateTime = time;
lastUpdate = time;
requestAnimationFrame(updateCursors);
}
/**
* @param {number} time
*/
function updateChars(time) {
if (!running) return;
const deltaTime = time - lastCharUpdateTime;
chars.forEach(char => {
char.update(deltaTime);
});
lastCharUpdateTime = time;
requestAnimationFrame(updateChars);
}
function cursorSetup() {
if (running) throw new Error('Only one instance of Cursor can run at a time.');
running = true;
@ -273,19 +261,82 @@ function cursorSetup() {
cursorContainer.id = 'cursors';
document.body.appendChild(cursorContainer);
myCursor = new Cursor(0, window.innerWidth / 2, window.innerHeight / 2);
myCursor = new Cursor("You!", window.innerWidth / 2, window.innerHeight / 2);
cursors.set(0, myCursor);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keypress', handleKeyPress);
document.addEventListener('keyup', handleKeyUp);
requestAnimationFrame(updateCursors);
requestAnimationFrame(updateChars);
console.debug(`Cursor tracking @ ${window.location.pathname}`);
ws = new WebSocket("/cursor-ws");
ws.addEventListener("open", () => {
console.log("Cursor connected to server successfully.");
ws.send(`loc:${window.location.pathname}`);
});
ws.addEventListener("error", error => {
console.error("Cursor WebSocket error:", error);
});
ws.addEventListener("close", () => {
console.log("Cursor connection closed.");
});
ws.addEventListener("message", event => {
const args = String(event.data).split(":");
if (args.length == 0) return;
let id = 0;
/** @type Cursor */
let cursor;
if (args.length > 1) {
id = Number(args[1]);
cursor = cursors.get(id);
}
switch (args[0]) {
case 'id': {
myCursor.setID(Number(args[1]));
break;
}
case 'join': {
if (id === myCursor.id) break;
cursors.set(id, new Cursor(id, 0, 0));
break;
}
case 'leave': {
if (!cursor || cursor === myCursor) break;
cursors.get(id).destroy();
cursors.delete(id);
break;
}
case 'char': {
if (!cursor || cursor === myCursor) break;
cursor.msg = args[2];
break;
}
case 'nochar': {
if (!cursor || cursor === myCursor) break;
cursor.msg = '';
break;
}
case 'pos': {
if (!cursor || cursor === myCursor) break;
cursor.move(Number(args[2]), Number(args[3]));
break;
}
default: {
console.warn("Cursor: Unknown command received from server:", args[0]);
break;
}
}
});
console.log(`Cursor tracking @ ${window.location.pathname}`);
}
function cursorDestroy() {
@ -294,13 +345,9 @@ function cursorDestroy() {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mouseup', handleMouseUp);
document.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('keypress', handleKeyPress);
document.removeEventListener('keyup', handleKeyUp);
chars.forEach(char => {
char.destroy();
});
chars = new Array();
cursors.forEach(cursor => {
cursor.destroy();
});
@ -309,7 +356,7 @@ function cursorDestroy() {
cursorContainer.remove();
console.debug(`Cursor no longer tracking.`);
console.log(`Cursor no longer tracking.`);
running = false;
}

View file

@ -20,15 +20,16 @@
border-color: var(--on-background) !important;
}
#cursors i.cursor .char {
#cursors i.char {
position: absolute;
transform: translateY(-44px);
margin: 0;
font-style: normal;
font-size: 20px;
font-weight: bold;
color: var(--on-background);
}
#cursors .funchar {
#cursors i.funchar {
position: absolute;
margin: 0;