首页 > 解决方案 > 我在跳跃脚本中做错了什么?

问题描述

我正在构建一个 2D 平台游戏。而且我还没有编写跳跃和所有这些的脚本,但是我有基本的脚本可以向各个方向移动:

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
      if (yVel <= 4){
        yVel += speed;
      }else{
        yVel = yVel
      }
      y -= yVel;

    }
    else if (e.keyCode == '40') {
      if (yVel <= 4){
        yVel += speed;
      }else{
        yVel = yVel
      }
      y += yVel;
    }
    else if (e.keyCode == '37') {
      if (xVel <= 4){
        xVel += speed;
      }else{
        xVel = xVel
      }
      x -= xVel;
    }
    else if (e.keyCode == '39') {
      if (xVel <= 4){
        xVel += speed;
      }else{
        xVel = xVel
      }
      x += xVel;
    }

结果应该是脚本,如果需要,它可以让你对角移动,但我得到的是当你按下向上键时,例如,它会上升,但是当你按下任何其他按钮时,例如,右,然后它停止向上运动,只向右走。有项目代码:https ://repl.it/@MarkelL/Break-It 这是项目本身:https ://break-it--markell.repl.co/

解释将非常感激。谢谢!

标签: javascript

解决方案


那是因为onKeyDown被第二次按键覆盖。您需要为您正在侦听的上/下键和左/右键(这样它们可以相互覆盖)编写一个事件侦听器 - 如果您使用的是像Phaser这样的 f2d 框架,他们已经指定了 keyDown 事件你可以绑定到。是一种检测多个按键的方法


推荐阅读