1

我试图让我的角色向左和向上移动,我认为 jump()函数slideLeft() 工作正常,问题出在controller(e)函数 ( else if (e.KeyCode===37)) 中。第一个功能可用,但无法访问第二个条件功能。另外,我想做一个slideRight()类似的功能后,我想让网格变成实心的,所以如果我的角色在上面跳跃,平台会支撑正方形。有人对我的任何一个问题有任何想法吗?

代码片段:

var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;


function jump() {
  if (isJumping) return
  let timerUpId = setInterval(function() {
    if (bottom > 250) {
      clearInterval(timerUpId);

      let timerDownId = setInterval(function() {
        if (bottom < 0) {
          clearInterval(timerDownId);
          isJumping = false;
        }
        bottom -= 5;
        square.style.bottom = bottom + 'px';
      }, 20)
    }
    isJumping = true;
    bottom += 30;
    square.style.bottom = bottom + 'px';
  }, 20)
}

function slideLeft() {
  console.log('da');
  isGoingLeft = true;
  leftTimerId = setInterval(function() {
    left -= 5;
    square.style.left = left + 'px';
  }, 20)
}

function controller(e) {
  if (e.keyCode === 32)
    jump();
  else if (e.KeyCode === 37)
    slideLeft();
}

document.addEventListener('keydown', controller);
.grid {
  position: absolute;
  background-color: chartreuse;
  height: 20px;
  width: 500px;
  bottom: 100px;
  left: 100px;
}

.square {
  position: absolute;
  background-color: darkblue;
  height: 100px;
  width: 100px;
  bottom: 0px;
  left: 150px;
}

`
<div class="grid"></div>
<div class="square"></div>

4

1 回答 1

1

编辑: 有一个错字:你第二次写KeyCode

function controller(e) {
    if(e.keyCode===32) {
        jump();
    }
    else if(e.keyCode===37) {
        slideLeft();
    }
}

我真的不明白你的问题的第二部分是什么意思。如果您希望角色能够在方块上跳跃,则必须实现碰撞检测。像这样的东西:

if ( isNotOnGround() ) { 
    fall() 
}
于 2022-02-09T14:11:12.553 回答