文章配图:Math.pow 与指数运算

页面预览

前言

在「猫猫大作战」中,重力下落是猫咪从棋盘顶部向下移动的物理模拟。猫咪在重力作用下逐行下落,直到碰到已着陆的猫咪或棋盘底部。

一、重力下落

private updateGravity(): void {
  const allCats = this.getAllCats();
  for (const cat of allCats) {
    if (!cat.falling) continue;

    // 计算落点
    const landingY = this.findLandingY(cat.x, cat.y);

    if (cat.y < landingY) {
      cat.y++;  // 下落 1 行
    } else {
      cat.falling = false;  // 着陆
      // 着陆后检测合并
      this.tryMergeAt(cat.x, cat.y);
    }
  }
}

private findLandingY(x: number, startY: number): number {
  for (let y = startY + 1; y < GameConfig.BOARD_HEIGHT; y++) {
    if (this.board[y][x] !== null) {
      return y - 1;
    }
  }
  return GameConfig.BOARD_HEIGHT - 1;
}

二、物理参数

参数 说明
更新周期 100ms 每帧更新位置
下落速度 1 行/帧 每次下落 1 行
着陆检测 下方格子非空 碰撞检测
合并检测 着陆后触发 递归合并链

三、下落效果

// 投放猫咪
function dropCat(col: number, level: CatLevel): void {
  const cat = new Cat(`cat_${Date.now()}`, level, col, 0, true);
  this.board[0][col] = cat;
  this.addCat(cat);
}

// 主循环(100ms 周期)
setInterval(() => {
  this.updateGravity();
  this.processMerges();
  if (this.isGameOver()) { this.endGame(); }
}, 100);

四、最佳实践

  1. 逐行下落:一次 1 行,模拟自然重力
  2. 着陆立即合并:落定后立刻触发合并检测
  3. 更新周期 100ms:60fps 下每 6 帧更新一次,性能友好

总结

重力下落通过逐行移动猫咪位置模拟物理下坠。核心要点:逐行下落直到落点、 着陆触发合并检测、 100ms 更新周期

如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!


相关资源:

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐