feat: 手机/平板触屏操作

- 自动识别触屏设备(coarse pointer + hover:none / 移动端 UA),桌面保持键鼠
- 左虚拟摇杆移动、右半屏滑动瞄准、开火/跳/换弹/切枪/菜单按键,真多点触控
- HUD 重排:血量与弹药上移,底部整条让给拇指;竖屏提示转屏
- 触屏搭车全屏 + 横屏锁定(Android),点开火保证至少一发,切后台自动松键
- 移动端 DPR 上限 1.3,枪模改离屏缓存,每帧只贴一次
- 观战自由视角同样支持摇杆;菜单打开时自动松开输入
This commit is contained in:
rong committed 2026-10-23 09:22:36 +08:00
1 parent 86f793ba34
commit 3506c33549
8 files changed
+997 -35

No files matched your search

+34 -4
View File
@@ -1,6 +1,6 @@
# CS · 枪火对决
第一人称 1v1 对枪。**Rust 权威服务端 + 纯静态 WebGL 前端**,打开网页就能打,不装客户端、不注册账号、前端零构建、零外部资源。
第一人称 1v1 对枪。**Rust 权威服务端 + 纯静态 WebGL 前端**,手机 / 平板 / 电脑打开网页就能打,不装客户端、不注册账号、前端零构建、零外部资源。
![大厅](docs/shot-lobby.png)
@@ -17,6 +17,7 @@ Rust(axum + tokio) public/ 里的 html/css/js 由同一个进程托
| --- | --- |
| ![战斗](docs/shot-game.png) | 第一人称视角、枪模、后坐力、准星、血量与弹药 |
| ![地图](docs/shot-map.png) | 48×48m 对称地图「沙漠据点」,中央高台 + 两侧小屋 + 掩体 |
| ![手机](docs/shot-mobile.png) | 手机横屏:左摇杆 + 右侧按键,HUD 自动让开拇指区域 |
## 跑起来
@@ -30,6 +31,31 @@ cargo run --release # 或 cargo run 走 debug,编译更快
首次编译约 3~5 分钟(拉依赖 + 编 axum/tokio),之后增量编译几秒。
## 手机上玩
前端会自己判断设备:`(pointer: coarse) and (hover: none)`,或 UA 明确是移动端,就切到触屏模式;
桌面(包括带触屏的笔记本,主指针是鼠标)仍然是键鼠 + 鼠标锁定。
> 建议**横屏**玩,竖屏会盖一层「把设备横过来」的提示。点「创建房间 / 练习模式 / 加入」时会顺带尝试全屏 + 锁定横屏
> (Android Chrome 支持;iOS Safari 不允许网页全屏,需要手动「添加到主屏幕」后横屏打开)。
| 触屏操作 | 作用 |
| --- | --- |
| 左下摇杆 | 移动(推到边缘是跑,轻推是走) |
| 右半屏滑动 | 转视角(拖动多少转多少,跟灵敏度挂钩) |
| 右下「开火」 | 按住连发;轻点也保证打出一发 |
| 「跳」 | 跳(能上 1 米矮台) |
| 「换弹」 | 换弹 |
| 「切枪」 | 步枪 / 手枪互换 |
| 右上「≡」 | 打开菜单(继续 / 灵敏度 / 离开) |
触屏模式下的几个细节:
- 左下角摇杆、右下角按键都是独立指针,**可以同时推摇杆 + 转视角 + 开枪**(真多点触控,不是模拟)。
- HUD 会重排:血量和弹药挪到屏幕上方,把底部整条让给两个拇指;击杀播报、记分板也跟着下移。
- 手指滑出按钮范围不会「卡住开火」,切后台 / 锁屏会自动松开所有按键。
- 手机和平板的渲染分辨率上限压到 1.3 倍 DPR,枪模烤成位图后每帧只贴一次,省电也省发热。
## 两个人怎么玩
**同一个 Wi-Fi(最简单)**
@@ -58,7 +84,7 @@ location / {
大厅里填房号点「观战」,就进入自由视角:WASD 飞、Shift 加速、鼠标转头。
两个座位都有人时,点「加入」也会自动变成观战。
## 操作
## 键鼠操作
| 按键 | 作用 |
| --- | --- |
@@ -98,7 +124,8 @@ public/style.css 深色科技风样式
public/level.json 地图数据(前后端同一份)
public/js/client/main.js 连接 / 输入 / 预测回滚 / 射击 / 回合 UI
public/js/client/renderer.js 手写 WebGL:贴图生成、地图合批、玩家模型、粒子、天空
public/js/client/viewmodel.js 第一人称枪模(2D Canvas 矢量绘制)
public/js/client/viewmodel.js 第一人称枪模(2D Canvas 矢量绘制 + 离屏缓存)
public/js/client/touch.js 触屏操作层:虚拟摇杆、滑动瞄准、开火/跳/换弹/切枪
public/js/client/movement.js 物理的 JS 镜像(客户端预测用)
public/js/client/weapons.js 武器表的 JS 镜像(只做表现)
public/js/client/sound.js WebAudio 现场合成(枪声 / 脚步 / 命中 / 换弹,无音频文件)
@@ -178,13 +205,16 @@ cargo test
单跑某一组:`cargo test --test e2e` / `cargo test 击杀`。
前端用无头 Chrome(`tools/verify.cjs`)做了真机视口验证:iPhone 844×390、iPad 1024×768、桌面 1440×900 三种环境,
分别确认触屏控件出现 / 隐藏、摇杆位移 4.36m、滑动转头 0.4rad、点射扣弹、换弹生效,控制台零报错。
## 还没做的
- 语音 / 文字聊天(cnchess 那套语音链路没搬过来,1v1 对枪用处也不大)
- 团队模式、经济系统、买枪、投掷物、穿墙伤害
- 地图只有一张,也没有编辑器(`tools/gen_level.py` 算半个)
- 房间状态在内存里,重启即清;也没做多进程横向扩展
- 移动端只有键鼠布局,触屏操作没做
- 触屏只做了横屏,竖屏直接提示转屏;也没有做手柄支持
- 反作弊:服务端已经拿走了所有裁定权,但没有做异常输入频率分析
## 本机编译加速 / 缓存布局
Binary file not shown.

After

Width:  |  Height:  |  Size: 598 KiB

+20
View File
@@ -135,6 +135,16 @@
</div>
</div>
<!-- ============================ 触屏操作层 ============================ -->
<div id="touch" hidden>
<div class="tstick" id="tStick"><i class="tknob" id="tKnob"></i></div>
<div class="tbtn fire" id="tFire"><span>开火</span></div>
<div class="tbtn jump" id="tJump"><span>跳</span></div>
<div class="tbtn small" id="tReload"><span>换弹</span></div>
<div class="tbtn small" id="tSwap"><span>切枪</span></div>
<div class="tbtn icon" id="tMenu"><span>≡</span></div>
</div>
<div id="waiting" hidden>
<div class="waiting-card">
<div class="pulse"></div>
@@ -191,6 +201,8 @@
<button class="btn primary" id="joinBtn">加入</button>
</div>
<p class="touch-tip">左摇杆移动 · 右侧滑动瞄准 · 按住「开火」射击</p>
<label class="slider">
<span>鼠标灵敏度 <b id="sensValLobby">1.0</b></span>
<input type="range" id="sensLobby" min="0.2" max="3" step="0.05" value="1" />
@@ -212,6 +224,14 @@
</div>
</div>
<div id="rotateHint">
<div class="rot-card">
<div class="rot-icon"></div>
<p>把设备横过来</p>
<p class="tiny">横屏才能看到完整的战场</p>
</div>
</div>
<div id="toast"></div>
<script type="module" src="/js/client/main.js"></script>
+105 -14
View File
@@ -8,6 +8,7 @@ import { Net } from "./net.js";
import { WEAPONS, weaponOf } from "./weapons.js";
import { stepBody, makeBody, K, MOVE } from "./movement.js";
import { ViewModel } from "./viewmodel.js";
import { Touch } from "./touch.js";
const $ = (id) => document.getElementById(id);
const TICK = 1 / 60;
@@ -17,6 +18,7 @@ const canvas = $("gl");
const hud = new Hud();
const sound = new Sound();
const viewmodel = new ViewModel(document.getElementById("vm"));
const touch = new Touch();
const renderer = (() => {
try {
return new Renderer(canvas);
@@ -83,6 +85,7 @@ const S = {
frames: 0,
fpsAt: performance.now(),
t: 0,
jumpUntil: 0,
demo: /(?:\?|&)demo=1/.test(location.search),
locked: false,
sens: 1,
@@ -138,6 +141,7 @@ function connect() {
function join(code, spectate) {
sound.ensure();
goFullscreen();
if (!code) {
toast("先输入 4 位房号");
return;
@@ -146,14 +150,31 @@ function join(code, spectate) {
send({ t: "join", code: code.trim().toUpperCase(), spectate: !!spectate });
}
function goFullscreen() {
if (!touch.enabled) return;
try {
const el = document.documentElement;
if (!document.fullscreenElement && el.requestFullscreen) {
el.requestFullscreen({ navigationUI: "hide" }).catch(() => {});
}
if (screen.orientation && screen.orientation.lock) {
screen.orientation.lock("landscape").catch(() => {});
}
} catch {
/* iOS Safari 不支持,忽略 */
}
}
function createRoom() {
sound.ensure();
goFullscreen();
wantRejoin = true;
send({ t: "create" });
}
function practice() {
sound.ensure();
goFullscreen();
wantRejoin = true;
send({ t: "create" });
S.pendingBot = true;
@@ -178,6 +199,7 @@ function leaveToLobby() {
hud.setSpectate(false);
$("matchOver").hidden = true;
lobby.hidden = false;
document.body.classList.remove("ingame");
if (document.pointerLockElement) document.exitPointerLock();
history.replaceState(null, "", location.pathname);
}
@@ -240,12 +262,18 @@ async function enterGame(msg) {
setTimeout(() => send({ t: "addBot" }), 120);
}
document.body.classList.add("ingame");
if (!S.demo) {
toast("点击画面锁定鼠标 · WASD 移动", 2600);
try {
await canvas.requestPointerLock();
} catch {
/* 需要用户点一下 */
if (touch.enabled) {
S.locked = true;
toast("左摇杆移动 · 右侧滑动瞄准 · 按住「开火」", 3600);
} else {
toast("点击画面锁定鼠标 · WASD 移动", 2600);
try {
await canvas.requestPointerLock();
} catch {
/* 需要用户点一下 */
}
}
}
hud.banner("沙漠据点", S.spectating ? "观战" : "准备", S.spectating ? "自由视角观看" : "每回合满血满弹 · 先到 8 分", 2000);
@@ -480,6 +508,23 @@ function onMatch(m) {
const keys = { fwd: false, back: false, left: false, right: false, jump: false, walk: false };
const mouse = { left: false };
/** 鼠标左键或触屏「开火」都算开火 */
function isFiring() {
return mouse.left || (touch.enabled && touch.fireHeld);
}
/** 触屏摇杆 / 跳跃 → 键位掩码 */
function touchMask() {
let k = 0;
const m = touch.move;
if (m.y < -0.3) k |= K.FWD;
if (m.y > 0.3) k |= K.BACK;
if (m.x < -0.3) k |= K.LEFT;
if (m.x > 0.3) k |= K.RIGHT;
if (performance.now() < S.jumpUntil) k |= K.JUMP;
return k;
}
function keyMask() {
let k = 0;
if (keys.fwd) k |= K.FWD;
@@ -569,7 +614,7 @@ window.addEventListener("keyup", (e) => {
});
canvas.addEventListener("mousedown", (e) => {
if (S.scene !== "game") return;
if (S.scene !== "game" || touch.enabled) return;
sound.ensure();
if (!document.pointerLockElement && !S.demo) {
canvas.requestPointerLock()?.catch?.(() => {});
@@ -602,6 +647,7 @@ document.addEventListener("mousemove", (e) => {
});
document.addEventListener("pointerlockchange", () => {
if (touch.enabled) return;
S.locked = document.pointerLockElement === canvas;
if (S.scene !== "game") return;
if (!S.locked && !S.demo && !S.matchOver) hud.pause(true);
@@ -609,11 +655,11 @@ document.addEventListener("pointerlockchange", () => {
});
document.addEventListener("pointerlockerror", () => {
if (S.scene === "game" && !S.demo) toast("浏览器拒绝了鼠标锁定,点一下画面再试");
if (S.scene === "game" && !S.demo && !touch.enabled) toast("浏览器拒绝了鼠标锁定,点一下画面再试");
});
canvas.addEventListener("click", () => {
if (S.scene === "game" && !S.locked && !S.demo) {
if (S.scene === "game" && !S.locked && !S.demo && !touch.enabled) {
canvas.requestPointerLock()?.catch?.(() => {});
}
});
@@ -646,7 +692,7 @@ function tryFire() {
const w = weaponOf(S.weapon);
const now = performance.now() / 1000;
if (S.reloadLeft > 0 || now < S.nextFire) return;
if (!mouse.left) return;
if (!isFiring()) return;
if (!w.auto && S.firedThisPress) return;
if (S.mag <= 0) {
@@ -760,6 +806,30 @@ function frame(now) {
}
function updateGame(dt) {
// 触屏:滑动瞄准 + 跳跃 / 换弹 / 切枪 / 菜单
if (touch.enabled) {
const d = touch.consumeLook();
if (d.x || d.y) {
const k = 0.0021 * S.sens * 1.45;
if (S.spectating) {
S.spec.yaw += d.x * k;
S.spec.pitch = clamp(S.spec.pitch - d.y * k, -1.5, 1.5);
} else {
S.yaw += d.x * k;
S.pitch = clamp(S.pitch - d.y * k, -1.53, 1.53);
}
}
if (touch.takeJump()) S.jumpUntil = performance.now() + 160;
if (touch.takeReload()) startReload();
if (touch.takeSwitch()) switchWeapon(S.weapon === 0 ? 1 : 0);
if (touch.takeMenu()) {
touch.fireHeld = false;
touch.move.x = 0;
touch.move.y = 0;
hud.pause(true);
}
}
// 预测修正残差衰减
const decay = Math.exp(-12 * dt);
S.err.x *= decay;
@@ -778,7 +848,7 @@ function updateGame(dt) {
S.shake = Math.max(0, S.shake - dt * 2.4);
S.reloadLeft = Math.max(0, S.reloadLeft - dt);
S.reloadPulse = Math.max(0, S.reloadPulse - dt);
if (!mouse.left) S.firedThisPress = false;
if (!isFiring()) S.firedThisPress = false;
// 死亡镜头下沉
if (!S.alive && !S.spectating) S.drop = Math.min(1, S.drop + dt * 3.2);
else if (S.alive) S.drop = Math.max(0, S.drop - dt * 6);
@@ -804,7 +874,7 @@ function updateGame(dt) {
function updatePlayer(dt) {
const live = S.phase === "live" && S.alive;
const keysNow = live ? keyMask() : 0;
const keysNow = live ? keyMask() | (touch.enabled ? touchMask() : 0) : 0;
acc += dt;
let steps = 0;
@@ -828,7 +898,7 @@ function updatePlayer(dt) {
keys: keysNow,
yaw: S.yaw,
pitch: S.pitch,
fire: mouse.left && live,
fire: isFiring() && live,
reload: S.reloadPulse > 0,
weapon: S.weapon,
});
@@ -866,7 +936,7 @@ function updatePlayer(dt) {
}
function updateSpectator(dt) {
const k = keyMask();
const k = keyMask() | (touch.enabled ? touchMask() : 0);
const yaw = S.spec.yaw;
const pitch = S.spec.pitch;
const cp = Math.cos(pitch);
@@ -1022,7 +1092,7 @@ $("codeInput").addEventListener("keydown", (e) => {
});
$("resumeBtn").addEventListener("click", () => {
hud.pause(false);
canvas.requestPointerLock()?.catch?.(() => {});
if (!touch.enabled) canvas.requestPointerLock()?.catch?.(() => {});
});
$("quitBtn").addEventListener("click", leaveToLobby);
$("specLeave").addEventListener("click", leaveToLobby);
@@ -1036,6 +1106,16 @@ $("waitBot").addEventListener("click", () => send({ t: "addBot" }));
$("joinBtn").addEventListener("click", () => sound.ensure());
$("practiceBtn").addEventListener("click", () => sound.ensure());
// 触屏上把"鼠标灵敏度"改成"触摸灵敏度",别误导人
if (touch.enabled) {
for (const id of ["sensValLobby", "sensVal"]) {
const node = document.getElementById(id);
if (node && node.parentNode && node.parentNode.firstChild) {
node.parentNode.firstChild.textContent = "触摸灵敏度 ";
}
}
}
const savedSens = parseFloat(localStorage.getItem("cs_sens") || "1");
S.sens = clamp(savedSens || 1, 0.2, 3);
for (const [input, label] of [
@@ -1059,6 +1139,17 @@ for (const [input, label] of [
const hash = location.hash.replace("#", "").trim().toUpperCase();
if (hash.length === 4) $("codeInput").value = hash;
window.addEventListener("resize", () => {
renderer.resize();
viewmodel.resize();
});
window.addEventListener("orientationchange", () => {
setTimeout(() => {
renderer.resize();
viewmodel.resize();
}, 260);
});
// 调试 / 自动化验证用(不影响游戏逻辑)
window.__CS = S;
window.__R = renderer;
+3 -1
View File
@@ -447,7 +447,9 @@ export class Renderer {
this.matBuffers = [];
this.shadowQuads = [];
this.cube = buildCube();
this.dpr = Math.min(window.devicePixelRatio || 1, 2);
const coarse =
window.matchMedia && window.matchMedia("(pointer: coarse)").matches;
this.dpr = Math.min(window.devicePixelRatio || 1, coarse ? 1.3 : 2);
this.progWorld = this.program(WORLD_VS, WORLD_FS);
this.progSky = this.program(SKY_VS, SKY_FS);
+314
View File
@@ -0,0 +1,314 @@
// 触屏操作层:左摇杆移动、右半屏滑动瞄准、开火 / 跳 / 换弹 / 切枪 / 菜单。
// 只在粗指针(手机、平板)上启用,桌面仍然走鼠标锁定 + 键盘。
export class Touch {
constructor() {
// 只在真正的手机 / 平板上启用:主指针是粗的、没有 hover,
// 或者 UA 明确是移动端(iPadOS 会伪装成 Mac,但带 Mobile 字样)。
const coarse = !!(window.matchMedia && window.matchMedia("(pointer: coarse)").matches);
const noHover = !!(window.matchMedia && window.matchMedia("(hover: none)").matches);
const mobileUA = /Mobile|Android|iPad|Tablet|iPod|iPhone/i.test(navigator.userAgent);
this.enabled = (coarse && noHover) || (coarse && mobileUA && (navigator.maxTouchPoints || 0) > 0);
this.move = { x: 0, y: 0 };
this.fireHeld = false;
this.jumpQueued = false;
this.reloadQueued = false;
this.switchQueued = false;
this.menuQueued = false;
this.look = { x: 0, y: 0 };
this.stickId = null;
this.lookId = null;
this.lx = 0;
this.ly = 0;
if (!this.enabled) return;
this.mount();
}
mount() {
this.root = document.getElementById("touch");
this.stick = document.getElementById("tStick");
this.knob = document.getElementById("tKnob");
if (!this.root || !this.stick || !this.knob) return;
document.body.classList.add("touch");
this.root.hidden = false;
this.root.setAttribute("aria-hidden", "false");
this.bindStick();
// 开火:按住连发,松手停(轻点也保证至少打出一发)
this.bindFire(document.getElementById("tFire"));
// 单次触发按键
this.bindTap(document.getElementById("tJump"), () => {
this.jumpQueued = true;
});
this.bindTap(document.getElementById("tReload"), () => {
this.reloadQueued = true;
});
this.bindTap(document.getElementById("tSwap"), () => {
this.switchQueued = true;
});
this.bindTap(document.getElementById("tMenu"), () => {
this.menuQueued = true;
});
this.bindLook();
this.watchBlur();
}
/* ------------------------------- 左摇杆 ------------------------------- */
bindStick() {
const stick = this.stick;
const knob = this.knob;
let cx = 0;
let cy = 0;
let radius = 1;
const place = (x, y) => {
let dx = x - cx;
let dy = y - cy;
const len = Math.hypot(dx, dy);
if (len > radius) {
dx = (dx / len) * radius;
dy = (dy / len) * radius;
}
knob.style.transform = `translate(calc(-50% + ${dx}px), calc(-50% + ${dy}px))`;
// 归一化:上推是前进(负数 y)
this.move.x = dx / radius;
this.move.y = dy / radius;
// 死区,避免手指微抖就走
if (Math.hypot(this.move.x, this.move.y) < 0.14) {
this.move.x = 0;
this.move.y = 0;
}
};
const reset = () => {
this.stickId = null;
this.move.x = 0;
this.move.y = 0;
knob.style.transform = "translate(-50%, -50%)";
stick.classList.remove("on");
};
stick.addEventListener(
"pointerdown",
(e) => {
if (this.stickId !== null) return;
e.preventDefault();
e.stopPropagation();
this.stickId = e.pointerId;
stick.setPointerCapture(e.pointerId);
stick.classList.add("on");
const r = stick.getBoundingClientRect();
cx = r.left + r.width / 2;
cy = r.top + r.height / 2;
radius = r.width * 0.42;
place(e.clientX, e.clientY);
},
{ passive: false }
);
stick.addEventListener(
"pointermove",
(e) => {
if (e.pointerId !== this.stickId) return;
e.preventDefault();
place(e.clientX, e.clientY);
},
{ passive: false }
);
for (const type of ["pointerup", "pointercancel", "pointerleave"]) {
stick.addEventListener(type, (e) => {
if (e.pointerId !== this.stickId) return;
reset();
});
}
}
/* ------------------------------- 右侧按键 ------------------------------- */
/** 开火键:点击至少保持 90ms,避免手快点一下就丢帧没打出子弹 */
bindFire(el) {
if (!el) return;
this.fireStart = 0;
el.addEventListener(
"pointerdown",
(e) => {
e.preventDefault();
e.stopPropagation();
el.classList.add("on");
try {
el.setPointerCapture(e.pointerId);
} catch {
/* ignore */
}
this.fireStart = performance.now();
this.fireHeld = true;
},
{ passive: false }
);
const release = () => {
el.classList.remove("on");
const start = this.fireStart;
const wait = Math.max(0, 90 - (performance.now() - start));
const done = () => {
if (this.fireStart === start) this.fireHeld = false;
};
if (wait > 0) setTimeout(done, wait);
else done();
};
el.addEventListener("pointerup", release);
el.addEventListener("pointercancel", release);
el.addEventListener("lostpointercapture", release);
el.addEventListener("contextmenu", (e) => e.preventDefault());
}
bindHold(el, down, up) {
if (!el) return;
const release = () => {
el.classList.remove("on");
up && up();
};
el.addEventListener(
"pointerdown",
(e) => {
e.preventDefault();
e.stopPropagation();
el.classList.add("on");
try {
el.setPointerCapture(e.pointerId);
} catch {
/* 老浏览器忽略 */
}
down && down();
},
{ passive: false }
);
el.addEventListener("pointerup", release);
el.addEventListener("pointercancel", release);
el.addEventListener("lostpointercapture", release);
el.addEventListener("contextmenu", (e) => e.preventDefault());
}
bindTap(el, fn) {
if (!el) return;
el.addEventListener(
"pointerdown",
(e) => {
e.preventDefault();
e.stopPropagation();
el.classList.add("on");
setTimeout(() => el.classList.remove("on"), 120);
fn();
},
{ passive: false }
);
el.addEventListener("contextmenu", (e) => e.preventDefault());
}
/* ------------------------------- 滑动瞄准 ------------------------------- */
bindLook() {
const surface = document.getElementById("gl");
if (!surface) return;
surface.addEventListener(
"pointerdown",
(e) => {
if (e.pointerType === "mouse") return;
if (this.lookId !== null) return;
e.preventDefault();
this.lookId = e.pointerId;
this.lx = e.clientX;
this.ly = e.clientY;
try {
surface.setPointerCapture(e.pointerId);
} catch {
/* ignore */
}
},
{ passive: false }
);
surface.addEventListener(
"pointermove",
(e) => {
if (e.pointerId !== this.lookId) return;
e.preventDefault();
this.look.x += e.clientX - this.lx;
this.look.y += e.clientY - this.ly;
this.lx = e.clientX;
this.ly = e.clientY;
},
{ passive: false }
);
const stop = (e) => {
if (e.pointerId !== this.lookId) return;
this.lookId = null;
};
surface.addEventListener("pointerup", stop);
surface.addEventListener("pointercancel", stop);
surface.addEventListener("contextmenu", (e) => e.preventDefault());
}
/** 切后台 / 失焦时松开所有输入,避免"卡住一直往前跑" */
watchBlur() {
const release = () => {
this.fireHeld = false;
this.move.x = 0;
this.move.y = 0;
this.stickId = null;
this.lookId = null;
if (this.knob) this.knob.style.transform = "translate(-50%, -50%)";
for (const el of document.querySelectorAll(".tbtn.on")) el.classList.remove("on");
};
window.addEventListener("blur", release);
document.addEventListener("visibilitychange", () => {
if (document.hidden) release();
});
}
/* -------------------------------- 读取端 -------------------------------- */
/** 取走这一帧的滑动量(像素) */
consumeLook() {
const d = { x: this.look.x, y: this.look.y };
this.look.x = 0;
this.look.y = 0;
return d;
}
takeJump() {
const v = this.jumpQueued;
this.jumpQueued = false;
return v;
}
takeReload() {
const v = this.reloadQueued;
this.reloadQueued = false;
return v;
}
takeSwitch() {
const v = this.switchQueued;
this.switchQueued = false;
return v;
}
takeMenu() {
const v = this.menuQueued;
this.menuQueued = false;
return v;
}
}
+41 -16
View File
@@ -8,7 +8,9 @@ export class ViewModel {
constructor(canvas) {
this.canvas = canvas;
this.g = canvas.getContext("2d");
this.dpr = Math.min(window.devicePixelRatio || 1, 2);
const coarse =
window.matchMedia && window.matchMedia("(pointer: coarse)").matches;
this.dpr = Math.min(window.devicePixelRatio || 1, coarse ? 1.3 : 2);
this.resize();
this.last = 0;
}
@@ -36,28 +38,20 @@ export class ViewModel {
const W = this.canvas.width;
const H = this.canvas.height;
const scale = (H / 720) * 1.04;
// 锚点:枪口大致在画面偏中下,枪身向右下角延伸
const ax = W * 0.53;
const ay = H * 0.585;
// 手机上把枪收小一点、往右下角挪,给拇指留出视野
const isTouch = document.body.classList.contains("touch");
const scale = (H / 720) * (isTouch ? 0.86 : 1.04);
const ax = W * (isTouch ? 0.55 : 0.53);
const ay = H * (isTouch ? 0.575 : 0.585);
const kick = s.kick || 0;
g.save();
g.translate(ax + (s.bobX || 0) * 700 + (s.swayX || 0) * 400 + kick * 26, ay + (s.bobY || 0) * 700 + kick * 10);
g.rotate(0.115 + kick * 0.02);
g.scale(scale, scale);
g.lineJoin = "round";
// 枪身投影
g.save();
g.globalAlpha = 0.28;
g.filter = "blur(10px)";
g.fillStyle = "#000";
g.fillRect(20, 110, 560, 180);
g.restore();
if (s.weapon === 1) this.drawPistol(g);
else this.drawRifle(g);
// 枪身是静态的,烤成位图后每帧只贴一次(手机上省很多)
g.drawImage(this.bake(s.weapon), -70, -70, 720, 420);
// 枪口火光
if (s.muzzle > 0) this.drawFlash(g, s.weapon === 1 ? [16, 96] : [14, 96], Math.min(1, s.muzzle * 16));
@@ -65,6 +59,37 @@ export class ViewModel {
g.restore();
}
/** 把整把枪画进离屏画布,缓存住(换枪才重画) */
bake(weaponId) {
if (this._cache && this._cacheId === weaponId) return this._cache;
const pad = 70;
const w = 720;
const h = 420;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const c = document.createElement("canvas");
c.width = Math.round(w * dpr);
c.height = Math.round(h * dpr);
const g = c.getContext("2d");
g.scale(dpr, dpr);
g.translate(pad, pad);
g.lineJoin = "round";
// 枪身投影
g.save();
g.globalAlpha = 0.3;
g.filter = "blur(9px)";
g.fillStyle = "#000";
g.fillRect(26, 108, 550, 176);
g.restore();
if (weaponId === 1) this.drawPistol(g);
else this.drawRifle(g);
this._cache = c;
this._cacheId = weaponId;
return c;
}
/* ------------------------------- 步枪 AK ------------------------------- */
drawRifle(g) {
+480
View File
@@ -1315,3 +1315,483 @@ input[type="range"]::-webkit-slider-thumb {
display: none;
}
}
/* ==========================================================================
触屏操作(手机 / 平板)
========================================================================== */
#touch {
inset: 0;
display: none;
pointer-events: none;
}
body.touch #touch {
display: block;
}
body.touch.ingame {
touch-action: none;
overscroll-behavior: none;
-webkit-user-select: none;
user-select: none;
}
body.touch.ingame #gl,
body.touch.ingame #vm {
touch-action: none;
}
body.touch .hud-right {
display: none;
}
/* 左摇杆 */
.tstick {
position: absolute;
left: calc(20px + env(safe-area-inset-left, 0px));
bottom: calc(20px + env(safe-area-inset-bottom, 0px));
width: clamp(104px, 19vh, 152px);
height: clamp(104px, 19vh, 152px);
border-radius: 50%;
border: 1.5px solid rgba(120, 200, 230, 0.3);
background: radial-gradient(circle at 50% 46%, rgba(18, 44, 62, 0.42), rgba(5, 10, 16, 0.5));
box-shadow: inset 0 0 26px rgba(56, 225, 255, 0.08), 0 8px 26px -14px #000;
pointer-events: auto;
touch-action: none;
-webkit-tap-highlight-color: transparent;
}
.tstick::before {
content: "";
position: absolute;
inset: 22%;
border-radius: 50%;
border: 1px dashed rgba(120, 200, 230, 0.18);
}
.tknob {
position: absolute;
left: 50%;
top: 50%;
width: 44%;
height: 44%;
border-radius: 50%;
transform: translate(-50%, -50%);
background: radial-gradient(circle at 38% 32%, rgba(186, 242, 255, 0.9), rgba(30, 122, 158, 0.8));
box-shadow: 0 0 18px rgba(56, 225, 255, 0.45), inset 0 0 10px rgba(255, 255, 255, 0.35);
will-change: transform;
}
/* 右侧按键 */
.tbtn {
position: absolute;
display: grid;
place-items: center;
border-radius: 50%;
border: 1.5px solid rgba(120, 200, 230, 0.3);
background: radial-gradient(circle at 40% 34%, rgba(26, 58, 80, 0.62), rgba(7, 14, 21, 0.58));
box-shadow: 0 6px 20px -10px #000, inset 0 1px 0 rgba(255, 255, 255, 0.08);
color: rgba(226, 246, 255, 0.92);
font-size: 12.5px;
font-weight: 600;
letter-spacing: 0.05em;
pointer-events: auto;
touch-action: none;
-webkit-tap-highlight-color: transparent;
transition: transform 0.06s ease, background 0.1s ease, border-color 0.1s ease;
}
.tbtn.on {
background: radial-gradient(circle at 40% 34%, rgba(56, 225, 255, 0.45), rgba(8, 52, 70, 0.7));
border-color: rgba(56, 225, 255, 0.85);
transform: scale(0.95);
}
.tbtn.fire {
right: calc(20px + env(safe-area-inset-right, 0px));
bottom: calc(20px + env(safe-area-inset-bottom, 0px));
width: clamp(76px, 14vh, 108px);
height: clamp(76px, 14vh, 108px);
font-size: 15px;
color: #ffe2cd;
border-color: rgba(255, 138, 61, 0.5);
background: radial-gradient(circle at 40% 34%, rgba(120, 52, 20, 0.55), rgba(24, 12, 8, 0.6));
box-shadow: 0 0 26px -10px rgba(255, 138, 61, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.1);
}
.tbtn.fire.on {
background: radial-gradient(circle at 40% 34%, rgba(255, 160, 80, 0.72), rgba(90, 34, 8, 0.8));
border-color: rgba(255, 180, 110, 0.95);
box-shadow: 0 0 34px -6px rgba(255, 138, 61, 0.85);
}
.tbtn.jump {
right: calc(134px + env(safe-area-inset-right, 0px));
bottom: calc(30px + env(safe-area-inset-bottom, 0px));
width: clamp(58px, 10vh, 76px);
height: clamp(58px, 10vh, 76px);
font-size: 13px;
}
.tbtn.small {
width: clamp(50px, 8.6vh, 66px);
height: clamp(50px, 8.6vh, 66px);
font-size: 11px;
}
#tReload {
right: calc(26px + env(safe-area-inset-right, 0px));
bottom: calc(132px + env(safe-area-inset-bottom, 0px));
}
#tSwap {
right: calc(100px + env(safe-area-inset-right, 0px));
bottom: calc(118px + env(safe-area-inset-bottom, 0px));
}
.tbtn.icon {
right: calc(12px + env(safe-area-inset-right, 0px));
top: calc(10px + env(safe-area-inset-top, 0px));
width: 40px;
height: 40px;
border-radius: 12px;
font-size: 17px;
font-weight: 400;
}
/* 触屏下的 HUD 重新排布:把血量和弹药挪到上面,底部全留给手 */
body.touch .hud-top {
padding: calc(8px + env(safe-area-inset-top, 0px)) calc(10px + env(safe-area-inset-right, 0px)) 0
calc(10px + env(safe-area-inset-left, 0px));
}
body.touch .scoreboard-mini {
padding: 5px 10px;
gap: 8px;
}
body.touch .scoreboard-mini .side b {
font-size: 18px;
}
body.touch .scoreboard-mini .tag {
font-size: 9px;
}
body.touch .roundbox {
padding: 0 8px;
gap: 8px;
}
body.touch .round-meta {
font-size: 9px;
}
body.touch .round-meta #roundTimer {
font-size: 11px;
}
body.touch .hud-bottom {
padding: 0;
}
.touch-tip {
display: none;
margin: 11px 0 0;
text-align: center;
font-size: 11px;
color: var(--dim);
letter-spacing: 0.02em;
}
body.touch .touch-tip {
display: block;
}
body.touch .hp-panel {
position: fixed;
left: calc(10px + env(safe-area-inset-left, 0px));
top: calc(56px + env(safe-area-inset-top, 0px));
min-width: 112px;
padding: 5px 10px 6px;
}
body.touch .hp-num {
font-size: 21px;
}
body.touch .hp-bar {
margin-top: 5px;
}
body.touch .hp-sub {
margin-top: 4px;
font-size: 9.5px;
}
body.touch .ammo-panel {
position: fixed;
right: calc(10px + env(safe-area-inset-right, 0px));
top: calc(54px + env(safe-area-inset-top, 0px));
min-width: 118px;
padding: 5px 10px 6px;
}
body.touch .wname {
font-size: 9.5px;
}
body.touch .ammo-row .mag {
font-size: 23px;
}
body.touch .ammo-row .reserve {
font-size: 11px;
}
body.touch .reload-track {
margin-top: 5px;
}
body.touch .whint {
display: none;
}
body.touch #killfeed {
top: calc(122px + env(safe-area-inset-top, 0px));
right: calc(10px + env(safe-area-inset-right, 0px));
}
body.touch .kf {
font-size: 10.5px;
padding: 4px 8px;
}
body.touch #spectateBar {
bottom: auto;
top: calc(118px + env(safe-area-inset-top, 0px));
font-size: 11px;
}
body.touch .banner-title {
font-size: 28px;
}
body.touch .banner-sub {
font-size: 12px;
}
body.touch .death-card {
padding: 18px 30px;
}
/* 竖屏提示 */
#rotateHint {
position: fixed;
inset: 0;
z-index: 60;
display: none;
place-items: center;
background: rgba(4, 8, 12, 0.96);
}
@media (orientation: portrait) {
body.touch #rotateHint {
display: grid;
}
}
.rot-card {
text-align: center;
color: var(--txt);
}
.rot-card p {
margin: 0;
font-size: 17px;
letter-spacing: 0.06em;
}
.rot-card .tiny {
margin-top: 6px;
font-size: 12px;
color: var(--dim);
letter-spacing: 0.04em;
}
.rot-icon {
width: 88px;
height: 58px;
margin: 0 auto 20px;
border: 2px solid var(--cyan);
border-radius: 10px;
box-shadow: 0 0 30px -8px rgba(56, 225, 255, 0.7);
animation: rot 2.6s ease-in-out infinite;
}
@keyframes rot {
0%,
22% {
transform: rotate(0deg);
}
55%,
82% {
transform: rotate(-90deg);
}
100% {
transform: rotate(-90deg);
}
}
/* 小屏 / 横屏矮窗口:大厅和大按钮适配 */
@media (max-width: 620px), (max-height: 520px) {
#lobby {
align-items: flex-start;
padding: 14px 12px;
}
.lobby-wrap {
width: min(440px, 100%);
}
.brand {
gap: 11px;
margin-bottom: 13px;
}
.logo {
width: 44px;
height: 44px;
}
.logo svg {
width: 26px;
height: 26px;
}
.brand-text h1 {
font-size: 19px;
}
.brand-text p {
font-size: 11px;
}
.lobby-card {
padding: 15px;
border-radius: 13px;
}
.tips {
font-size: 11px;
line-height: 1.7;
padding: 10px 12px;
margin-top: 12px;
}
.tips li:nth-child(3) {
display: none;
}
.code-input {
font-size: 17px;
padding: 9px 4px 9px 12px;
}
.btn {
min-height: 44px;
}
.pause-card,
.match-card {
width: min(340px, 92vw);
padding: 20px;
}
.sb-card {
width: min(420px, 94vw);
}
.sb-head,
.sb-row {
grid-template-columns: 1fr 54px 54px 70px;
padding: 9px 12px;
font-size: 11.5px;
}
}
/* 手机横屏(矮窗口):大厅压到一屏内 */
@media (max-height: 520px) {
body.touch #lobby {
align-items: center;
padding: 10px 12px;
}
body.touch .lobby-wrap {
width: min(720px, 100%);
display: grid;
grid-template-columns: 200px 1fr;
gap: 18px;
align-items: start;
}
body.touch .brand {
flex-direction: column;
align-items: flex-start;
gap: 8px;
margin: 0;
}
body.touch .brand-text h1 {
font-size: 17px;
}
body.touch .brand-text p {
font-size: 10.5px;
line-height: 1.6;
}
body.touch .lobby-card {
padding: 12px 14px;
}
body.touch .map-strip {
padding-bottom: 8px;
margin-bottom: 9px;
}
body.touch .btn.big {
padding: 11px 16px;
font-size: 15px;
}
body.touch .lobby-row {
margin-top: 8px;
}
body.touch .lobby-row .btn {
padding: 8px 10px;
}
body.touch .or {
margin: 9px 0 7px;
}
body.touch .code-input {
padding: 7px 4px 7px 12px;
font-size: 15px;
}
body.touch .slider {
margin-top: 9px;
font-size: 11px;
}
body.touch .tips,
body.touch .lobby-foot,
body.touch .net-row {
display: none;
}
body.touch .btn kbd {
display: none;
}
}
.touch-tip {
display: none;
margin: 11px 0 0;
text-align: center;
font-size: 11px;
color: var(--dim);
letter-spacing: 0.02em;
}
body.touch .touch-tip {
display: block;
}
body.touch .hp-panel {
top: calc(60px + env(safe-area-inset-top, 0px));
}
body.touch .ammo-panel {
top: calc(56px + env(safe-area-inset-top, 0px));
}
body.touch #killfeed {
top: calc(128px + env(safe-area-inset-top, 0px));
}