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

如何用JavaScript实现车辆向右移动?已完成向左移动功能

实现车辆向右移动的逻辑

你已经通过反向计算索引实现了车辆左移,要让右侧车辆向右移动,只需要调整位置匹配的逻辑,直接用计数器模间隔值来对应索引即可。

修改后的完整关键代码如下:

//! Variables
const width = 9
const height = 8
const cellCount = width * height
const cells = []
let counter = 0
let timer

//! Car movement
// car1
const carRowIndexLeft = 6
const carGapLeft = 2
const carStartIndexLeft = width * carRowIndexLeft 
let carsLeft = []

// car2
const carRowIndexRight = 4
const carGapRight = 2
const carStartIndexRight = width * carRowIndexRight
let carsRight = []

//!Creating a grid function
function createGrid() {
  for (let i = 0; i < cellCount; i++) {
    const cell = document.createElement('div')
    cell.innerText = i
    cell.dataset.index = i
    cells.push(cell)
    grid.appendChild(cell) 
  }
  carsLeft = Array.from(cells).slice(carStartIndexLeft, carStartIndexLeft + width)
  carsRight = Array.from(cells).slice(carStartIndexRight, carStartIndexRight + width)
}

// Starting the game
function startGame() {
  timer = setInterval(() => {
    counter++
    cells.forEach(cell => cell.classList.remove('car1', 'car2'))

    // 左移车辆逻辑
    carsLeft.forEach((car, i) => {
      if (i % carGapLeft === carGapLeft - 1 - counter % carGapLeft){
        car.classList.add('car1')
      }
    })

    // 右移车辆逻辑
    carsRight.forEach((car, i) => {
      // 用计数器模间隔值匹配索引,实现向右推进
      if (i % carGapRight === counter % carGapRight) {
        car.classList.add('car2')
      }
    })
  }, 500)
}

逻辑说明

  • 左移逻辑:通过carGapLeft - 1 - counter % carGapLeft反向计算匹配索引,让车辆从右往左依次移动
  • 右移逻辑:直接用counter % carGapRight匹配索引,计数器每增加1,匹配的索引就向右推进一位,实现车辆从左往右移动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:24:27