feat(player): add avatar-centered drag steering

This commit is contained in:
2026-09-09 23:15:00 +03:00
parent 381eacf403
commit 1396bad76d
27 changed files with 307 additions and 451 deletions
+137 -72
View File
@@ -8,13 +8,15 @@
const MAX_VIEW_CELLS = 1024;
const MAX_VIEW_OBJECTS = 12;
const OBSERVER_CELL_SIZE = 8;
const JOYSTICK_DEAD_ZONE = 20;
const JOYSTICK_HYSTERESIS = .18;
const JOYSTICK_SLOW_REPEAT_MS = 360;
const JOYSTICK_FAST_REPEAT_MS = 170;
const AVATAR_TOUCH_TARGET_SIZE = 96;
const AVATAR_MAX_DEFLECTION = 28;
const AVATAR_DEAD_ZONE = 12;
const AVATAR_DIRECTION_HYSTERESIS = .18;
const AVATAR_SLOW_REPEAT_MS = 360;
const AVATAR_FAST_REPEAT_MS = 170;
const LATENCY_SAMPLE_LIMIT = 256;
const ONBOARDING_STEPS = Object.freeze([
Object.freeze({icon: "hand", title: "Потяни кружок", text: "Кружок ведёт героя по лабиринту."}),
Object.freeze({icon: "hand", title: "Потяни героя", text: "Потяни героя — лабиринт поедет под ним."}),
Object.freeze({icon: "motion", title: "Отпусти — герой ждёт", text: "Рука остановилась — шаги тоже."}),
Object.freeze({icon: "maze", title: "Стена не пускает", text: "Упрись в стену — попробуй другую сторону."}),
Object.freeze({icon: "key", title: "Найди ключ", text: "Ключ открывает твой выход."}),
@@ -107,36 +109,71 @@
return Math.min(maximum, Math.max(minimum, value));
}
function joystickDirection(dx, dy, previousDirection) {
function avatarDirection(dx, dy, previousDirection) {
const horizontal = Math.abs(dx);
const vertical = Math.abs(dy);
if (Math.max(horizontal, vertical) < JOYSTICK_DEAD_ZONE) return null;
if (Math.max(horizontal, vertical) < AVATAR_DEAD_ZONE) return null;
const previousWasHorizontal = previousDirection === "east" || previousDirection === "west";
const previousWasVertical = previousDirection === "north" || previousDirection === "south";
if (previousWasHorizontal && horizontal >= vertical * (1 - JOYSTICK_HYSTERESIS)) return dx >= 0 ? "east" : "west";
if (previousWasVertical && vertical >= horizontal * (1 - JOYSTICK_HYSTERESIS)) return dy >= 0 ? "south" : "north";
if (previousWasHorizontal && horizontal >= vertical * (1 - AVATAR_DIRECTION_HYSTERESIS)) return dx >= 0 ? "east" : "west";
if (previousWasVertical && vertical >= horizontal * (1 - AVATAR_DIRECTION_HYSTERESIS)) return dy >= 0 ? "south" : "north";
return horizontal >= vertical ? (dx >= 0 ? "east" : "west") : (dy >= 0 ? "south" : "north");
}
function joystickRepeatMs(distance, radius) {
if (!Number.isFinite(distance) || !Number.isFinite(radius) || distance <= JOYSTICK_DEAD_ZONE || radius <= JOYSTICK_DEAD_ZONE) return null;
const strength = clamp((distance - JOYSTICK_DEAD_ZONE) / (radius - JOYSTICK_DEAD_ZONE), 0, 1);
return Math.round(JOYSTICK_SLOW_REPEAT_MS - (JOYSTICK_SLOW_REPEAT_MS - JOYSTICK_FAST_REPEAT_MS) * strength);
function avatarRepeatMs(distance, targetRadius) {
if (!Number.isFinite(distance) || !Number.isFinite(targetRadius) || distance <= AVATAR_DEAD_ZONE || targetRadius <= AVATAR_DEAD_ZONE) return null;
const strength = clamp((distance - AVATAR_DEAD_ZONE) / (targetRadius - AVATAR_DEAD_ZONE), 0, 1);
return Math.round(AVATAR_SLOW_REPEAT_MS - (AVATAR_SLOW_REPEAT_MS - AVATAR_FAST_REPEAT_MS) * strength);
}
function joystickVector(dx, dy, radius, previousDirection) {
function avatarVector(dx, dy, targetRadius, previousDirection) {
const distance = Math.hypot(dx, dy);
const boundedDistance = Math.min(distance, radius);
const ratio = distance > 0 ? boundedDistance / distance : 0;
const inputDistance = Math.min(distance, targetRadius);
const deflection = Math.min(inputDistance, AVATAR_MAX_DEFLECTION);
const ratio = distance > 0 ? deflection / distance : 0;
return {
x: dx * ratio,
y: dy * ratio,
distance: boundedDistance,
direction: joystickDirection(dx, dy, previousDirection),
repeatMs: joystickRepeatMs(boundedDistance, radius)
distance: deflection,
direction: avatarDirection(dx, dy, previousDirection),
repeatMs: avatarRepeatMs(inputDistance, targetRadius)
};
}
class LatestIntentFlow {
constructor(dispatch) {
this.dispatch = dispatch;
this.inFlight = null;
this.latest = null;
}
request(direction) {
if (!direction) return null;
if (this.inFlight) {
this.latest = direction;
return null;
}
const requestId = this.dispatch(direction);
if (requestId) this.inFlight = requestId;
return requestId;
}
complete(requestId) {
if (!requestId || requestId !== this.inFlight) return null;
this.inFlight = null;
const direction = this.latest;
this.latest = null;
return direction ? this.request(direction) : null;
}
release() { this.latest = null; }
disconnect() {
this.inFlight = null;
this.latest = null;
}
}
function playerCellSize(stageWidth, stageHeight, columns, rows) {
if (![stageWidth, stageHeight, columns, rows].every(value => Number.isFinite(value) && value > 0)) return 46;
return Math.round(clamp(Math.min(stageWidth / (columns + 1), stageHeight / (rows + 1)), 32, 72));
@@ -151,6 +188,7 @@
this.now = typeof now === "function" ? now : () => root.performance.now();
this.pending = new Map();
this.samples = [];
this.pointerSamples = [];
}
sent(requestId) {
@@ -178,6 +216,14 @@
}
snapshot() { return this.samples.map(sample => Object.assign({}, sample)); }
pointerPainted(startedAt) {
if (!Number.isFinite(startedAt)) return;
this.pointerSamples.push(this.now() - startedAt);
if (this.pointerSamples.length > LATENCY_SAMPLE_LIMIT) this.pointerSamples.shift();
}
pointerSnapshot() { return this.pointerSamples.slice(); }
}
function createEnvelope(type, sequence, requestId, payload) {
@@ -244,7 +290,8 @@
function boot(documentObject, windowObject) {
const byId = id => documentObject.getElementById(id);
const state = {socket: null, clientSequence: 0, serverSequence: 0, viewSequence: -1, session: null, lobby: null, snapshot: null, reconnectTimer: null, noticeTimer: null, touchStart: null, pending: new Map(), assembler: new SnapshotAssembler(), latency: new LatencyTracker(() => windowObject.performance.now()), audio: null, feedbackReady: false, muted: false, reducedMotion: false, onboardingSeen: false, onboardingStep: 0, joystick: {pointerId: null, direction: null, repeatTimer: null, repeatMs: null}, observer: {scale: 1, x: 0, y: 0, dragging: null}};
const state = {socket: null, clientSequence: 0, serverSequence: 0, viewSequence: -1, session: null, lobby: null, snapshot: null, reconnectTimer: null, noticeTimer: null, touchStart: null, pending: new Map(), assembler: new SnapshotAssembler(), latency: new LatencyTracker(() => windowObject.performance.now()), audio: null, feedbackReady: false, muted: false, reducedMotion: false, onboardingSeen: false, onboardingStep: 0, avatar: {pointerId: null, direction: null, repeatTimer: null, repeatMs: null}, observer: {scale: 1, x: 0, y: 0, dragging: null}};
state.moveFlow = new LatestIntentFlow(direction => sendMoveNow(direction));
function showNotice(text, kind) {
const element = byId("notice");
@@ -272,7 +319,7 @@
byId("connection").dataset.state = connectionState;
byId("connection-text").textContent = text;
byId("details-text").textContent = connectionState === "online" ? "WebSocket подключён к локальному ESP." : "Команды временно не отправляются. Повторяем подключение автоматически.";
if (connectionState !== "online") resetJoystick();
if (connectionState !== "online") resetAvatarControl();
}
renderWelcomeHeadline(randomLoginHeadline());
@@ -416,7 +463,6 @@
if (!(data.passages & 8)) cell.classList.add("wall-w");
(objects.get(data.index) || []).forEach(object => addObject(cell, object));
const slot = state.session ? state.session.slot : 1;
if (data.index === snapshot.self) addPawn(cell, characterForSlot(slot).symbol, false);
if (data.index === snapshot.opponent) addPawn(cell, characterForSlot(slot === 1 ? 2 : 1).symbol, true);
maze.appendChild(cell);
});
@@ -434,6 +480,8 @@
const character = characterForSlot(slot);
byId("self-slot").textContent = character.symbol;
byId("self-slot").setAttribute("aria-label", character.name);
byId("avatar-handle-symbol").textContent = character.symbol;
byId("avatar-control").setAttribute("aria-label", `Тянуть героя ${character.name} для движения`);
byId("self-name").textContent = playerName();
byId("identity").className = `identity player-${slot === 1 ? "one" : "two"}`;
byId("match-screen").classList.toggle("player-two-mode", slot === 2);
@@ -451,7 +499,7 @@
if (Number.isInteger(snapshot.stateSequence)) {
windowObject.requestAnimationFrame(() => state.latency.painted(snapshot.stateSequence));
}
if (snapshot.phase === "paused") { resetJoystick(); showModal("Пауза", "Один герой потерялся между Wi‑Fi пакетами. Ждём возвращения.", "ПЕРЕРЫВ", false); }
if (snapshot.phase === "paused") { resetAvatarControl(); showModal("Пауза", "Один герой потерялся между Wi‑Fi пакетами. Ждём возвращения.", "ПЕРЕРЫВ", false); }
else if (snapshot.phase === "finished" || snapshot.result && snapshot.result !== "none") renderResult(snapshot.result);
else {
hideModal();
@@ -554,7 +602,7 @@
text = slot ? (winner === slot ? "Вы официально быстрее очень большого куста." : "Соперник нашёл выход. Лабиринт требует реванш.") : "Зрительный зал фиксирует героический побег без вмешательства в результат.";
}
showModal(title, text, "ГОНКА ЗАВЕРШЕНА", false);
resetJoystick();
resetAvatarControl();
byId("modal-action").textContent = state.session && state.session.role === "player" && state.session.slot === 1 ? "Новая гонка" : "Вернуться в лобби";
byId("modal-action").hidden = false;
}
@@ -590,9 +638,10 @@
} else if (message.type === "pause") { showModal("Пауза", `Игрок ${message.payload.slot || "?"} переподключается. Ноги пока не считаются.`, "ЖДЁМ СВЯЗЬ", false);
} else if (message.type === "resume") { hideModal(); showNotice("Оба героя снова на связи. Гонка продолжается.", "success");
} else if (message.type === "match_result") { renderResult(message.payload.result);
} else if (message.type === "reset") { state.snapshot = null; state.viewSequence = -1; state.assembler = new SnapshotAssembler(); resetJoystick(); hideModal(); setScreen("lobby"); showNotice("Лабиринт пересажен. Можно начинать новую гонку.", "success");
} else if (message.type === "ack") { state.latency.acknowledged(message.requestId, message.payload && message.payload.stateSequence); feedback(true);
} else if (message.type === "reset") { state.snapshot = null; state.viewSequence = -1; state.assembler = new SnapshotAssembler(); resetAvatarControl(); hideModal(); setScreen("lobby"); showNotice("Лабиринт пересажен. Можно начинать новую гонку.", "success");
} else if (message.type === "ack") { state.latency.acknowledged(message.requestId, message.payload && message.payload.stateSequence); state.moveFlow.complete(message.requestId); feedback(true);
} else if (message.type === "error") {
state.moveFlow.complete(message.requestId);
if (message.payload.code === "invalid_token") { windowObject.localStorage.removeItem(TOKEN_KEY); state.session = null; setScreen("welcome"); }
if (message.payload.code === "blocked") { const bump = byId("wall-bump"); bump.textContent = localError("blocked"); bump.classList.remove("show"); void bump.offsetWidth; bump.classList.add("show"); }
showNotice(localError(message.payload.code), "error"); feedback(false);
@@ -605,48 +654,63 @@
state.socket = new windowObject.WebSocket(`${scheme}://${windowObject.location.host}/ws`);
state.socket.onopen = () => { setConnection("online", "ESP на связи"); const token = windowObject.localStorage.getItem(TOKEN_KEY); if (token) send("restore", {token}, null); };
state.socket.onmessage = event => { let message; try { message = JSON.parse(event.data); } catch (_) { showNotice("Сервер прислал нечитаемый пакет.", "error"); return; } handleMessage(message); };
state.socket.onclose = () => { setConnection("offline", "Связь потеряна"); state.reconnectTimer = windowObject.setTimeout(connect, 1000); };
state.socket.onclose = () => { state.moveFlow.disconnect(); setConnection("offline", "Связь потеряна"); state.reconnectTimer = windowObject.setTimeout(connect, 1000); };
state.socket.onerror = () => showNotice("WebSocket споткнулся. Пробуем снова…", "error");
}
function move(direction, element) {
if (direction) send("move", {direction}, element || documentObject.querySelector(`[data-direction="${direction}"]`));
if (direction) state.moveFlow.request(direction, element);
}
function resetJoystick() {
windowObject.clearTimeout(state.joystick.repeatTimer);
state.joystick.pointerId = null;
state.joystick.direction = null;
state.joystick.repeatTimer = null;
state.joystick.repeatMs = null;
const joystick = byId("joystick");
const handle = byId("joystick-handle");
if (joystick) joystick.classList.remove("active");
function sendMoveNow(direction) {
return send("move", {direction}, byId("avatar-control"));
}
function resetAvatarControl() {
windowObject.clearTimeout(state.avatar.repeatTimer);
state.avatar.pointerId = null;
state.avatar.direction = null;
state.avatar.repeatTimer = null;
state.avatar.repeatMs = null;
state.moveFlow.release();
const control = byId("avatar-control");
const handle = byId("avatar-handle");
if (control) {
control.classList.remove("active");
control.removeAttribute("data-direction");
control.dataset.speed = "stop";
}
if (handle) handle.style.transform = "translate(-50%, -50%)";
}
function repeatJoystickMove() {
const joystick = state.joystick;
if (!joystick.direction || joystick.pointerId == null || !joystick.repeatMs) return;
move(joystick.direction, byId("joystick"));
joystick.repeatTimer = windowObject.setTimeout(repeatJoystickMove, joystick.repeatMs);
function repeatAvatarMove() {
const avatar = state.avatar;
if (!avatar.direction || avatar.pointerId == null || !avatar.repeatMs) return;
move(avatar.direction);
avatar.repeatTimer = windowObject.setTimeout(repeatAvatarMove, avatar.repeatMs);
}
function updateJoystick(event) {
const joystick = byId("joystick");
const rect = joystick.getBoundingClientRect();
const radius = Math.max(1, Math.min(rect.width, rect.height) / 2 - 33);
const vector = joystickVector(event.clientX - (rect.left + rect.width / 2), event.clientY - (rect.top + rect.height / 2), radius, state.joystick.direction);
byId("joystick-handle").style.transform = `translate(calc(-50% + ${vector.x}px), calc(-50% + ${vector.y}px))`;
const directionChanged = vector.direction !== state.joystick.direction;
state.joystick.direction = vector.direction;
state.joystick.repeatMs = vector.repeatMs;
windowObject.clearTimeout(state.joystick.repeatTimer);
state.joystick.repeatTimer = null;
function updateAvatarControl(event) {
const pointerStartedAt = windowObject.performance.now();
const control = byId("avatar-control");
const rect = control.getBoundingClientRect();
const radius = Math.max(AVATAR_DEAD_ZONE + 1, Math.min(rect.width, rect.height) / 2);
const vector = avatarVector(event.clientX - (rect.left + rect.width / 2), event.clientY - (rect.top + rect.height / 2), radius, state.avatar.direction);
const handle = byId("avatar-handle");
handle.style.transform = `translate(calc(-50% + ${vector.x}px), calc(-50% + ${vector.y}px))`;
const directionChanged = vector.direction !== state.avatar.direction;
state.avatar.direction = vector.direction;
state.avatar.repeatMs = vector.repeatMs;
control.dataset.speed = vector.repeatMs == null ? "stop" : vector.repeatMs <= 220 ? "fast" : "slow";
if (vector.direction) control.dataset.direction = vector.direction;
else control.removeAttribute("data-direction");
windowObject.clearTimeout(state.avatar.repeatTimer);
state.avatar.repeatTimer = null;
if (vector.direction) {
if (directionChanged) move(vector.direction, joystick);
state.joystick.repeatTimer = windowObject.setTimeout(repeatJoystickMove, vector.repeatMs);
if (directionChanged) move(vector.direction);
state.avatar.repeatTimer = windowObject.setTimeout(repeatAvatarMove, vector.repeatMs);
}
windowObject.requestAnimationFrame(() => state.latency.pointerPainted(pointerStartedAt));
}
function setMuted(muted) {
@@ -671,26 +735,27 @@
beginFeedback();
const direction = directionFromKey(event.code); if (direction) { event.preventDefault(); move(direction, null); }
});
byId("map-shell").addEventListener("touchstart", event => { const touch = event.changedTouches[0]; state.touchStart = {x: touch.clientX, y: touch.clientY}; }, {passive: true});
byId("map-shell").addEventListener("touchend", event => { if (!state.touchStart) return; const touch = event.changedTouches[0]; move(directionFromSwipe(state.touchStart.x, state.touchStart.y, touch.clientX, touch.clientY), null); state.touchStart = null; }, {passive: true});
byId("joystick").addEventListener("pointerdown", event => {
byId("map-shell").addEventListener("touchstart", event => { if (event.target.closest("#avatar-control")) return; const touch = event.changedTouches[0]; state.touchStart = {x: touch.clientX, y: touch.clientY}; }, {passive: true});
byId("map-shell").addEventListener("touchend", event => { if (event.target.closest("#avatar-control") || !state.touchStart) return; const touch = event.changedTouches[0]; move(directionFromSwipe(state.touchStart.x, state.touchStart.y, touch.clientX, touch.clientY), null); state.touchStart = null; }, {passive: true});
byId("avatar-control").addEventListener("pointerdown", event => {
event.preventDefault();
beginFeedback();
state.joystick.pointerId = event.pointerId;
byId("joystick").classList.add("active");
if (byId("joystick").setPointerCapture) byId("joystick").setPointerCapture(event.pointerId);
updateJoystick(event);
state.avatar.pointerId = event.pointerId;
byId("avatar-control").classList.add("active");
if (byId("avatar-control").setPointerCapture) byId("avatar-control").setPointerCapture(event.pointerId);
updateAvatarControl(event);
});
byId("joystick").addEventListener("pointermove", event => {
if (event.pointerId === state.joystick.pointerId) updateJoystick(event);
byId("avatar-control").addEventListener("pointermove", event => {
if (event.pointerId === state.avatar.pointerId) updateAvatarControl(event);
});
const stopJoystick = event => {
if (event.pointerId === state.joystick.pointerId) resetJoystick();
const stopAvatarControl = event => {
if (event.pointerId === state.avatar.pointerId) resetAvatarControl();
};
byId("joystick").addEventListener("pointerup", stopJoystick);
byId("joystick").addEventListener("pointercancel", stopJoystick);
windowObject.addEventListener("blur", resetJoystick);
documentObject.addEventListener("visibilitychange", () => { if (documentObject.hidden) resetJoystick(); });
byId("avatar-control").addEventListener("pointerup", stopAvatarControl);
byId("avatar-control").addEventListener("pointercancel", stopAvatarControl);
byId("avatar-control").addEventListener("lostpointercapture", stopAvatarControl);
windowObject.addEventListener("blur", resetAvatarControl);
documentObject.addEventListener("visibilitychange", () => { if (documentObject.hidden) resetAvatarControl(); });
documentObject.querySelectorAll("[data-direction]").forEach(button => button.addEventListener("click", () => move(button.dataset.direction, button)));
byId("drop-key").addEventListener("click", () => send("drop_key", {}, byId("drop-key")));
byId("mute-toggle").addEventListener("click", () => setMuted(!state.muted));
@@ -729,10 +794,10 @@
}
});
connect();
return {state, handleMessage, move, resetJoystick, latencySamples: () => state.latency.snapshot()};
return {state, handleMessage, move, resetAvatarControl, latencySamples: () => state.latency.snapshot(), pointerFeedbackSamples: () => state.latency.pointerSnapshot()};
}
const api = Object.freeze({TOKEN_KEY, MAX_VIEW_CHUNKS, NAME_COMBINATION_COUNT, LOGIN_HEADLINES, ONBOARDING_STEPS, LATENCY_SAMPLE_LIMIT, JOYSTICK_DEAD_ZONE, JOYSTICK_HYSTERESIS, JOYSTICK_SLOW_REPEAT_MS, JOYSTICK_FAST_REPEAT_MS, LatencyTracker, directionFromKey, directionFromSwipe, joystickDirection, joystickRepeatMs, joystickVector, playerCellSize, nextOnboardingStep, randomIndex, randomSuggestedName, randomLoginHeadline, createEnvelope, snapshotIsValid, SnapshotAssembler, projectedCellIndices, clampObserverZoom, observerFitScale, boot});
const api = Object.freeze({TOKEN_KEY, MAX_VIEW_CHUNKS, NAME_COMBINATION_COUNT, LOGIN_HEADLINES, ONBOARDING_STEPS, LATENCY_SAMPLE_LIMIT, AVATAR_TOUCH_TARGET_SIZE, AVATAR_MAX_DEFLECTION, AVATAR_DEAD_ZONE, AVATAR_DIRECTION_HYSTERESIS, AVATAR_SLOW_REPEAT_MS, AVATAR_FAST_REPEAT_MS, LatestIntentFlow, LatencyTracker, directionFromKey, directionFromSwipe, avatarDirection, avatarRepeatMs, avatarVector, playerCellSize, nextOnboardingStep, randomIndex, randomSuggestedName, randomLoginHeadline, createEnvelope, snapshotIsValid, SnapshotAssembler, projectedCellIndices, clampObserverZoom, observerFitScale, boot});
if (typeof module !== "undefined" && module.exports) module.exports = api;
root.Maze32Player = api;
if (root.document) root.document.addEventListener("DOMContentLoaded", () => { root.maze32PlayerApp = boot(root.document, root); });