为什么我的JS Shmup将镜头向右移动?

问题描述 投票:0回答:1

我正在尝试修改Jared Mills的现有JS / HTML5 shmup,使其垂直移动并更改精灵。更改精灵很容易。逻辑最有效。但是,在渲染镜头和碰撞检测方面存在很多问题。代码“似乎”可以正常工作……但是镜头没有以正确的方式出现。

这是我的相关代码(其余代码均未激活。我所做的只是向空格键发送垃圾邮件以“开枪”(调用fireLaser()),请观看随附的动画GIF。假定画布为400x400像素,请使用此格式

 fireLaser() {
  let laser = createLaserElement()
  mainPlayArea.appendChild(laser)
  moveLaser(laser)
}


function createLaserElement() {
  let xPosition = parseInt(window.getComputedStyle(shooter).getPropertyValue('left')) // assume 180px
  let yPosition = parseInt(window.getComputedStyle(shooter).getPropertyValue('top')) // assume 350px
  let newLaser = document.createElement('img')
  newLaser.src = 'images/bullet.png' // green paw
  newLaser.classList.add('laser')
  newLaser.style.left = `${xPosition-40}px` // should be +10, but... 
  newLaser.style.top = `${yPosition-20}px`
  return newLaser
}


function moveLaser(laser) {
  let laserInterval = setInterval(() => {
    let yPosition = parseInt(laser.style.top)
    let monsters = document.querySelectorAll(".monster")
    monsters.forEach(monster => {
      if (checkLaserCollision(laser, monster)) {
        monster.src = "images/explosion.png"   // dead skull
        monster.classList.remove("monster")
        monster.classList.add("dead-monster")
        scoreCounter.innerText = parseInt(scoreCounter.innerText) + 100
      }
    })
    if (yPosition <= 40) {  // shot didn't hit anything and reached the tp
      laser.remove()  // erase it
    } else {
      laser.style.top = `${yPosition - 4}px`  // move 4 pixels up
    }
  }, 10)
}

Recording of my "cat" shooting, but there was no movement...

[好像“激光”被“猫”和“激光”的其他渲染向侧面移位。当每一个都被擦除时,下一个莫名其妙地被“置换”了回来。我在Chrome检查器中检查了.left……它们都是一样的。因此,它仅在渲染中。我怀疑没有必要在createLaserElement中使用-40 x偏移量。但是,如果我没有它,那张照片就是从那只猫的尾巴出来的。这似乎没有任何意义。

我做错了什么?

javascript html dom html5-canvas
1个回答
0
投票

我发布问题的那一刻,我意识到问题不在代码中,而是随附的样式表中,抱歉。样式表将对象称为position:relative,从而弄乱了坐标。将其更改为绝对值后,问题自行解决。

© www.soinside.com 2019 - 2024. All rights reserved.