feat(player): add avatar-centered drag steering
This commit is contained in:
+1
-1
@@ -52,11 +52,11 @@
|
||||
<div class="map-shell" id="map-shell" tabindex="0" aria-label="Лабиринт. Используйте стрелки, WASD или свайпы для движения">
|
||||
<div class="unknown-message" id="map-placeholder"><svg aria-hidden="true"><use href="/icons.svg#radar"></use></svg><span>Ждём разрешённый сервером кусочек карты…</span></div>
|
||||
<div class="maze" id="maze" role="img" aria-label="Видимая часть лабиринта"></div>
|
||||
<button class="avatar-control" id="avatar-control" type="button" aria-label="Тянуть героя для движения"><span class="avatar-handle" id="avatar-handle" aria-hidden="true"><span id="avatar-handle-symbol">●</span><svg><use href="/icons.svg#arrow"></use></svg></span></button>
|
||||
<div class="wall-bump" id="wall-bump" role="status" aria-live="polite"></div>
|
||||
</div>
|
||||
<div class="child-controls" aria-label="Игровые действия">
|
||||
<button class="drop-key" id="drop-key" type="button" aria-label="Сбросить ключ" disabled><svg aria-hidden="true"><use href="/icons.svg#key"></use></svg><strong>OK</strong><span>бросить</span></button>
|
||||
<div class="joystick" id="joystick" role="application" aria-label="Джойстик движения"><span class="joystick-ring" aria-hidden="true"></span><span class="joystick-handle" id="joystick-handle" aria-hidden="true"><svg><use href="/icons.svg#arrow"></use></svg></span></div>
|
||||
</div>
|
||||
<div class="access-controls" aria-label="Настройки игры">
|
||||
<button class="access-button" id="mute-toggle" type="button" aria-label="Выключить звук"><svg aria-hidden="true"><use href="/icons.svg#sound"></use></svg></button>
|
||||
|
||||
+13
-7
@@ -137,13 +137,21 @@ input:focus { border-color: var(--aqua); box-shadow: 0 0 0 3px #43ead229; }
|
||||
.wall-bump.show { animation: bump .8s steps(3, end); }
|
||||
.wall-bump::before { content: "▌"; display: inline-block; margin-right: 6px; font-size: 1.35em; font-weight: 1000; }
|
||||
|
||||
.avatar-control { position: absolute; z-index: 8; left: 50%; top: 50%; width: 96px; height: 96px; margin: -48px; padding: 0; border: 0; border-radius: 50%; background: transparent; cursor: grab; touch-action: none; user-select: none; }
|
||||
.avatar-control:active, .avatar-control.active { cursor: grabbing; }
|
||||
.avatar-handle { position: absolute; left: 50%; top: 50%; width: 52px; height: 52px; display: grid; place-items: center; border: 3px solid currentColor; border-radius: 50%; background: #0b0712; color: var(--p1); box-shadow: 4px 4px 0 #000, 0 0 0 3px #43ead236; font-size: 1.25rem; font-weight: 1000; transform: translate(-50%, -50%); transition: transform .12s steps(3, end); }
|
||||
.player-two-mode .avatar-handle { color: var(--p2); }
|
||||
.avatar-control.active .avatar-handle { transition: none; }
|
||||
.avatar-handle svg { position: absolute; width: 19px; height: 19px; right: -13px; top: -13px; display: none; padding: 2px; border: 1px solid currentColor; background: #08050b; color: var(--aqua); }
|
||||
.avatar-control[data-direction] .avatar-handle svg { display: block; }
|
||||
.avatar-control[data-direction="north"] .avatar-handle svg { transform: rotate(0deg); }
|
||||
.avatar-control[data-direction="east"] .avatar-handle svg { transform: rotate(90deg); }
|
||||
.avatar-control[data-direction="south"] .avatar-handle svg { transform: rotate(180deg); }
|
||||
.avatar-control[data-direction="west"] .avatar-handle svg { transform: rotate(270deg); }
|
||||
.avatar-control[data-speed="fast"] .avatar-handle { box-shadow: 4px 4px 0 #000, 0 0 0 4px var(--aqua), 0 0 18px #43ead299; }
|
||||
.avatar-control[data-speed="slow"] .avatar-handle { box-shadow: 4px 4px 0 #000, 0 0 0 3px #43ead270; }
|
||||
.child-controls { position: absolute; z-index: 12; inset: auto 0 12px; display: flex; align-items: end; justify-content: space-between; padding: 0 16px; pointer-events: none; }
|
||||
.child-controls > * { pointer-events: auto; }
|
||||
.joystick { position: relative; width: 180px; height: 180px; border: 5px solid var(--aqua); border-radius: 50%; background: #102a30dd; box-shadow: inset 0 0 0 12px #43ead214, 5px 5px 0 #020506; touch-action: none; user-select: none; }
|
||||
.joystick-ring { position: absolute; inset: 18px; border: 2px dashed #43ead266; border-radius: 50%; }
|
||||
.joystick-handle { position: absolute; left: 50%; top: 50%; width: 66px; height: 66px; display: grid; place-items: center; border: 3px solid var(--ink); border-radius: 50%; background: var(--aqua); color: #06211f; box-shadow: 4px 4px 0 #020506; transform: translate(-50%, -50%); transition: transform .08s linear; }
|
||||
.joystick-handle svg { width: 38px; height: 38px; }
|
||||
.joystick.active .joystick-handle { transition: none; }
|
||||
.access-controls { position: absolute; z-index: 14; top: 92px; right: 8px; display: grid; gap: 6px; }
|
||||
.access-button { width: 42px; height: 42px; display: grid; place-items: center; border: 2px solid var(--aqua); border-radius: 50%; background: #102a30e8; color: var(--aqua); box-shadow: 3px 3px 0 #020506; }
|
||||
.access-button svg { width: 24px; height: 24px; }
|
||||
@@ -242,7 +250,6 @@ input:focus { border-color: var(--aqua); box-shadow: 0 0 0 3px #43ead229; }
|
||||
.stat svg { width: 27px; height: 27px; flex-basis: 27px; }
|
||||
.map-shell { inset: 82px 0 0; }
|
||||
.child-controls { bottom: max(14px, env(safe-area-inset-bottom)); padding: 0 10px; }
|
||||
.joystick { width: 172px; height: 172px; }
|
||||
.drop-key { position: relative; top: auto; right: auto; bottom: auto; width: 78px; height: 78px; }
|
||||
.access-controls { top: 88px; right: 8px; }
|
||||
.dpad { display: none; }
|
||||
@@ -262,7 +269,6 @@ input:focus { border-color: var(--aqua); box-shadow: 0 0 0 3px #43ead229; }
|
||||
.identity, .stat { min-height: 55px; }
|
||||
.map-shell { inset: 64px 0 0; }
|
||||
.drop-key { top: 76px; right: 14px; width: 70px; height: 70px; }
|
||||
.joystick { width: 150px; height: 150px; }
|
||||
}
|
||||
|
||||
@media (hover: none) and (pointer: coarse) and (max-height: 720px) {
|
||||
|
||||
+137
-72
@@ -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); });
|
||||
|
||||
Reference in New Issue
Block a user