You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript网格对象移动:单函数替代左右移动双函数方案

单函数实现角色左右移动方案

方案1:条件判断式单函数

逻辑直观,适配简单的双向移动场景:

// 角色X轴位置,假设网格坐标范围为0-9(对应10x10网格)
let playerX = 5;

function move(direction) {
  // 边界校验,防止角色移出网格
  if (direction === 'left') {
    playerX = Math.max(0, playerX - 1);
  } else if (direction === 'right') {
    playerX = Math.min(9, playerX + 1);
  }
}

方案2:映射式单函数(更易扩展)

如果后续计划添加上下移动等方向,用对象映射的方式会更简洁且便于维护:

let playerX = 5;

// 定义各方向的移动逻辑
const moveHandlers = {
  left: () => playerX = Math.max(0, playerX - 1),
  right: () => playerX = Math.min(9, playerX + 1)
};

function move(direction) {
  // 执行对应方向的移动,非法输入会被自动忽略
  moveHandlers[direction]?.();
}

使用时直接调用move('left')或move('right')即可,两种方案都整合了原有的moveLeft()和moveRight()逻辑,实现了单函数控制。

内容的提问来源于stack exchange,提问作者user19932377

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:30:58