🎮ArcadeLab

网格地图 · 丝滑平移摇杆

by EpicCoder88
457 lines12.7 KB
▶ Play
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>网格地图 · 丝滑平移摇杆</title>
<style>
  *{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
  html,body{
    margin:0;padding:10px 8px 160px;min-height:100%;
    background:#0a0e13;color:#cfe6ff;
    font:14px/1.5 ui-monospace,Consolas,monospace;
    display:flex;flex-direction:column;align-items:center;gap:10px;
    user-select:none;-webkit-user-select:none;touch-action:manipulation;
    overflow-x:hidden;
  }
  canvas{display:block;max-width:100%;background:#0f1419;border-radius:10px;
    box-shadow:0 0 0 1px rgba(120,200,255,.15),0 10px 30px rgba(0,0,0,.6);}
  #hud{font-size:12px;color:#8fb4d6;text-align:center;line-height:1.7}
  #hud b{color:#ffbe50}

  /* —— 摇杆 UI —— */
  #joystick-container {
    position: fixed;
    bottom: 36px;
    right: 32px;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: rgba(15, 25, 35, 0.55);
    border: 2px solid rgba(120, 200, 255, 0.25);
    box-shadow: inset 0 0 20px rgba(0,0,0,0.5);
    touch-action: none;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
  }
  #joystick-knob {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(120,200,255,0.85), rgba(50,120,180,0.85));
    box-shadow: 0 0 12px rgba(120, 200, 255, 0.4), inset 0 -3px 6px rgba(0,0,0,0.2);
    position: absolute;
    pointer-events: none;
    transition: transform 0.05s linear;
  }

  /* —— 障碍编辑按钮 —— */
  #modeBtn{
    position: fixed;
    bottom: 70px;
    left: 32px;
    border: 1px solid rgba(120,200,255,.25);
    border-radius: 12px;
    background: rgba(30,50,70,.65);
    color: #bcd8f5;
    padding: 10px 16px;
    font: inherit;
    z-index: 100;
    touch-action: manipulation;
  }
  #modeBtn.on{
    background: rgba(220,120,120,.35);
    color: #ffd6d6;
    border-color: rgba(255,120,120,.55);
  }
</style>
</head>
<body>
<canvas id="map"></canvas>
<div id="hud"></div>

<div id="joystick-container">
  <div id="joystick-knob"></div>
</div>
<button id="modeBtn">编辑障碍:关</button>

<script>
/* =========================================================
 * 1. 配置
 * =======================================================*/
const CFG = {
  cols: 20,
  rows: 14,
  cell: 36,
  pad : 44,
  color: {
    grid   : 'rgba(120,200,255,0.30)',
    label  : 'rgba(150,190,225,0.85)',
    hover  : 'rgba(120,200,255,0.10)',
    block  : 'rgba(255,120,120,0.35)',
  }
};

const canvas  = document.getElementById('map');
const ctx     = canvas.getContext('2d');
const hud     = document.getElementById('hud');
const modeBtn = document.getElementById('modeBtn');

let W = 0, H = 0;
let hover = null;
const blocks = new Set();
let editMode = false;

/* =========================================================
 * 2. 坐标工具
 * =======================================================*/
const key = (c, r) => c + ',' + r;
const inRange = (c, r) => c >= 0 && c < CFG.cols && r >= 0 && r < CFG.rows;
const cellToPixel  = (c, r) => ({ x: CFG.pad + c * CFG.cell,      y: CFG.pad + r * CFG.cell });
function pixelToCell(x, y) {
  const c = Math.floor((x - CFG.pad) / CFG.cell);
  const r = Math.floor((y - CFG.pad) / CFG.cell);
  return inRange(c, r) ? { col: c, row: r } : null;
}

/* =========================================================
 * 3. 小人设置(使用浮点数坐标)
 * =======================================================*/
const hero = {
  x: 2.0, y: 2.0,       // 小人占据 [x, x+1] 宽,[y, y+2] 高
  skin : '#ffcf5c',
  cloth: '#4ea8de',
  line : '#10161d',
};

/** AABB 包围盒碰撞检测 */
function checkCollision(x, y) {
  // 边界检测
  if (x < 0 || x + 1 > CFG.cols || y < 0 || y + 2 > CFG.rows) return true;

  // 障碍物检测
  for (const k of blocks) {
    const [bx, by] = k.split(',').map(Number);
    // 矩形相交:x轴重叠 且 y轴重叠
    if (x < bx + 1 && x + 1 > bx && y < by + 1 && y + 2 > by) {
      return true;
    }
  }
  return false;
}

function drawCharacter(x, y, opt = {}) {
  const w  = CFG.cell;
  const h  = CFG.cell * 2;
  const px = CFG.pad + x * CFG.cell;   // 将格子浮点坐标转为像素
  const py = CFG.pad + y * CFG.cell;
  const cx = px + w / 2;

  const skin  = opt.skin  || hero.skin;
  const cloth = opt.cloth || hero.cloth;
  const line  = opt.line  || hero.line;

  // 脚下阴影
  ctx.beginPath();
  ctx.ellipse(cx, py + h - w * 0.05, w * 0.30, w * 0.08, 0, 0, Math.PI * 2);
  ctx.fillStyle = 'rgba(0,0,0,0.35)';
  ctx.fill();

  // 身体
  const neckY   = py + w * 0.60;
  const footY   = py + h - w * 0.08;
  const topHalf = w * 0.22;
  const botHalf = w * 0.36;

  ctx.beginPath();
  ctx.moveTo(cx - topHalf, neckY);
  ctx.lineTo(cx + topHalf, neckY);
  ctx.lineTo(cx + botHalf, footY);
  ctx.lineTo(cx - botHalf, footY);
  ctx.closePath();
  ctx.fillStyle = cloth;
  ctx.fill();
  ctx.lineWidth = Math.max(1.5, w * 0.055);
  ctx.strokeStyle = line;
  ctx.stroke();

  // 头
  const r  = w * 0.24;
  const hy = py + w * 0.18 + r;
  ctx.beginPath();
  ctx.arc(cx, hy, r, 0, Math.PI * 2);
  ctx.fillStyle = skin;
  ctx.fill();
  ctx.stroke();
}

/* =========================================================
 * 4. 画布与绘制
 * =======================================================*/
function initCanvas() {
  const vw   = Math.min(document.documentElement.clientWidth || 9999, window.innerWidth);
  const maxW = Math.min(vw - 16, 880);

  let cell = Math.floor(maxW / (CFG.cols + 2.5));
  cell = Math.max(12, Math.min(40, cell));
  let pad  = Math.max(22, Math.round(cell * 1.25));
  while (2 * pad + CFG.cols * cell > maxW && cell > 12) {
    cell--;
    pad = Math.max(22, Math.round(cell * 1.25));
  }

  CFG.cell = cell;
  CFG.pad  = pad;
  W = 2 * pad + CFG.cols * cell;
  H = 2 * pad + CFG.rows * cell;

  const dpr = window.devicePixelRatio || 1;
  canvas.width  = Math.round(W * dpr);
  canvas.height = Math.round(H * dpr);
  canvas.style.width  = W + 'px';
  canvas.style.height = H + 'px';
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}

function fillCell(col, row, color) {
  const p = cellToPixel(col, row);
  ctx.fillStyle = color;
  ctx.fillRect(p.x, p.y, CFG.cell, CFG.cell);
}

function dashLine(x1, y1, x2, y2) {
  const d = Math.max(3, Math.min(6, CFG.cell * 0.16));
  ctx.setLineDash([d, d]);
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.stroke();
  ctx.setLineDash([]);
}

function drawGrid() {
  ctx.lineWidth = 1;
  ctx.strokeStyle = CFG.color.grid;
  const x0 = CFG.pad, y0 = CFG.pad;
  const x1 = CFG.pad + CFG.cols * CFG.cell;
  const y1 = CFG.pad + CFG.rows * CFG.cell;

  for (let c = 0; c <= CFG.cols; c++) dashLine(x0 + c * CFG.cell, y0, x0 + c * CFG.cell, y1);
  for (let r = 0; r <= CFG.rows; r++) dashLine(x0, y0 + r * CFG.cell, x1, y0 + r * CFG.cell);
}

function drawLabels() {
  const fs = Math.max(8, Math.round(CFG.cell * 0.30));
  ctx.font = fs + 'px ui-monospace, Consolas, monospace';
  ctx.fillStyle = CFG.color.label;
  ctx.textBaseline = 'middle';

  ctx.textAlign = 'center';
  for (let c = 0; c < CFG.cols; c++) ctx.fillText(c, CFG.pad + (c + .5) * CFG.cell, CFG.pad - fs - 4);

  ctx.textAlign = 'right';
  for (let r = 0; r < CFG.rows; r++) ctx.fillText(r, CFG.pad - 6, CFG.pad + (r + .5) * CFG.cell);
}

function draw() {
  ctx.clearRect(0, 0, W, H);

  for (const k of blocks) {
    const [c, r] = k.split(',').map(Number);
    fillCell(c, r, CFG.color.block);
  }

  if (hover) fillCell(hover.col, hover.row, CFG.color.hover);

  drawGrid();
  drawLabels();
  // 传入浮点坐标,实现平滑渲染
  drawCharacter(hero.x, hero.y);
}

function updateHud() {
  hud.innerHTML = `小人当前位置 <b>(${hero.x.toFixed(2)}, ${hero.y.toFixed(2)})</b> 障碍 <b>${blocks.size}</b>`;
}

/* =========================================================
 * 5. 摇杆输入状态
 * =======================================================*/
const joystick = {
  active: false,
  baseX: 0, baseY: 0,
  maxRadius: 40,
  vx: 0, vy: 0   // 归一化的输入向量(-1 到 1)
};

const container = document.getElementById('joystick-container');
const knob = document.getElementById('joystick-knob');

container.addEventListener('pointerdown', e => {
  e.preventDefault();
  joystick.active = true;
  const rect = container.getBoundingClientRect();
  joystick.baseX = rect.left + rect.width / 2;
  joystick.baseY = rect.top + rect.height / 2;
  updateJoystick(e.clientX, e.clientY);
});

window.addEventListener('pointermove', e => {
  if (!joystick.active) return;
  updateJoystick(e.clientX, e.clientY);
});

window.addEventListener('pointerup', endJoystick);
window.addEventListener('pointercancel', endJoystick);

function updateJoystick(clientX, clientY) {
  let dx = clientX - joystick.baseX;
  let dy = clientY - joystick.baseY;
  const dist = Math.hypot(dx, dy);

  if (dist > joystick.maxRadius) {
    dx = (dx / dist) * joystick.maxRadius;
    dy = (dy / dist) * joystick.maxRadius;
  }
  
  knob.style.transform = `translate(${dx}px, ${dy}px)`;

  // 死区判断(推程太短不移动)
  if (dist > 15) {
    const realDist = Math.hypot(dx, dy);
    // 归一化方向向量,支持斜角
    joystick.vx = dx / realDist;
    joystick.vy = dy / realDist;
  } else {
    joystick.vx = 0;
    joystick.vy = 0;
  }
}

function endJoystick() {
  if (!joystick.active) return;
  joystick.active = false;
  knob.style.transform = `translate(0px, 0px)`;
  joystick.vx = 0;
  joystick.vy = 0;
}

/* =========================================================
 * 6. 主循环与平移物理引擎
 * =======================================================*/
const SPEED = 0.06; // 每帧移动 0.06 格(约 3.6格/秒)
let lastTime = performance.now();

function gameLoop(now) {
  // 计算帧时间差,保证不同刷新率下手感一致
  const dt = Math.min((now - lastTime) / 16.66, 2); 
  lastTime = now;

  if (joystick.vx !== 0 || joystick.vy !== 0) {
    const vx = joystick.vx * SPEED * dt;
    const vy = joystick.vy * SPEED * dt;

    // 轴分离检测:X轴移动不碰壁就允许X移动
    if (!checkCollision(hero.x + vx, hero.y)) {
      hero.x += vx;
    }
    // Y轴移动不碰壁就允许Y移动(如果X被墙挡住,依然可以沿着墙上下滑动)
    if (!checkCollision(hero.x, hero.y + vy)) {
      hero.y += vy;
    }
    
    // 微调:防止精确卡在 0.999 这种边缘
    if (Math.abs(hero.x) < 0.001) hero.x = 0;
    if (Math.abs(hero.y) < 0.001) hero.y = 0;
  }

  draw();
  updateHud();
  requestAnimationFrame(gameLoop);
}

/* =========================================================
 * 7. 其他交互(键盘、编辑障碍)
 * =======================================================*/
// 键盘输入映射到摇杆向量
let keys = {};
window.addEventListener('keydown', e => {
  if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
    e.preventDefault();
    keys[e.key] = true;
    updateKeyInput();
  }
});
window.addEventListener('keyup', e => {
  if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
    keys[e.key] = false;
    updateKeyInput();
  }
});
function updateKeyInput() {
  if (joystick.active) return; // 触摸优先
  let vx = 0, vy = 0;
  if (keys['ArrowUp']) vy -= 1;
  if (keys['ArrowDown']) vy += 1;
  if (keys['ArrowLeft']) vx -= 1;
  if (keys['ArrowRight']) vx += 1;
  
  if (vx !== 0 || vy !== 0) {
    const dist = Math.hypot(vx, vy);
    joystick.vx = vx / dist;
    joystick.vy = vy / dist;
  } else {
    joystick.vx = 0;
    joystick.vy = 0;
  }
}

function eventToCell(e) {
  const rect = canvas.getBoundingClientRect();
  const x = (e.clientX - rect.left) * (W / rect.width);
  const y = (e.clientY - rect.top)  * (H / rect.height);
  return pixelToCell(x, y);
}

canvas.addEventListener('pointerdown', e => {
  e.preventDefault();
  const cell = eventToCell(e);
  if (!cell) return;

  if (editMode) {
    // 检查格子是否与小人包围盒重叠,重叠则不放置
    if (cell.col < hero.x + 1 && cell.col + 1 > hero.x &&
        cell.row < hero.y + 2 && cell.row + 1 > hero.y) {
      return;
    }
    const k = key(cell.col, cell.row);
    blocks.has(k) ? blocks.delete(k) : blocks.add(k);
  } else {
    // 点击瞬移(如果目标没有障碍物)
    if (!checkCollision(cell.col, cell.row)) {
      hero.x = cell.col;
      hero.y = cell.row;
    }
  }
});

modeBtn.addEventListener('click', () => {
  editMode = !editMode;
  modeBtn.classList.toggle('on', editMode);
  modeBtn.textContent = '编辑障碍:' + (editMode ? '开' : '关');
});

let rzTimer;
window.addEventListener('resize', () => {
  clearTimeout(rzTimer);
  rzTimer = setTimeout(() => { initCanvas(); draw(); }, 120);
});

/* 启动 */
initCanvas();
updateHud();
requestAnimationFrame(gameLoop);
</script>
</body>
</html>

Game Source: 网格地图 · 丝滑平移摇杆

Creator: EpicCoder88

Libraries: none

Complexity: complex (457 lines, 12.7 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: game-epiccoder88-mx1dic7a" to link back to the original. Then publish at arcadelab.ai/publish.