如何使用 javascript 对角线移动精灵?

How to move sprite diagonally with javascript?

我正在制作一个 HTML5 canvas 的 2-D 平台游戏风格的游戏。在其中,角色可以使用箭头键跳跃和左右移动,除了一个问题外,它工作正常。当我跳跃并同时移动到一边时,精灵会上升并且不会移动到一边。只有当它下降时,它才能正常移动。有办法解决吗?我已经对其他 "move sprite diagonally" 问题进行了研究,但根据我的代码;当我放开 'up' 键时,精灵 应该 移动到一边,对吧?看看我的代码,看看你的想法......

**注意:就好像我已经定义了变量一样,因为我有

        window.addEventListener("keydown", checkKeyPressed, false);
        //^don't proceed if you don't know what this means^

        function checkKeyPressed(e) {

            if (e.keyCode == "38" && jumpTime == 0) {
                //checks if 'up' key is pressed then initiates the 'jump' sequence

                refreshIntervalId = setInterval(jumpUp, 5);//calls the jump function

                setTimeout(stopRefresh, 500);//sets time until character stops jumping

                jumpCal();//temporarily disables jumping, and therefore a double-jump

            }else if (e.keyCode == "37") {
                //checks if 'left' key is pressed then moves sprite to the side 
                charX = charX - 8;//piece 1,
                a = a - 8;//2,
                c = c - 8;//and 3
            }else if (e.keyCode == "39") {
                //same thing, except to the right...
                charX = charX + 8;
                a = a + 8;
                c = c + 8;
            }
        }

        function jumpUp()  {
            charY = charY - 5;//moves up pieces 1,
            b = b - 5;//2,
            d = d - 5;//and 3, since the sprite is composed of three images
        }

        function stopRefresh()  {
            clearInterval(refreshIntervalId);
            //stops the character from jumping
        }

        function jumpCal()  {
            jumpTime = 1;
            setTimeout(jumpRes, 1750);
            //times out the jumping action
        }

        function jumpRes()  {
            jumpTime = 0;
            //resets the jumping action
        }

        function gravityControl()  {

            if (charY <= platformDetect) {
                //checks if touching platform then moves all pieces down
                charY = charY + 3;//piece 1
                b = b + 3;//piece 2
                d = d + 3;//piece 3
                //this function is called multiple times in an unspecified piece of code, so no, I did not make an error here
            }
        }

        function detectPlatform()  {

            platformDetect = 160;
            //I've added this function because there will be platforms later in the game
        }

你看懂我的代码了吗?我有遗漏什么吗?是不是太马虎了?如果您有任何与问题无关的建议,请随时将其添加到评论中,我很乐意接受。

回到手头的话题,我的代码对吗?因为当我点击'up'键然后松开并按住'right'键时,我的角色轨迹如下:

第 1 步:

              ^
              |
              |
              |
              |
              |
              |
              |

**上升正常,但没有像预期的那样移动到一边

第 2 步:

              |_
                |_
                  |_
                    |_
                      |
                      |_
                        |
                       \ /

** 下来并像它应该的那样移动到一边

你能帮帮我吗?如果我解释的任何部分你没看懂我会在评论中接受批评,毕竟我想变得更好。

                       _                _
                      |@|              |@|

                              /_

                   ---___             ___---
                         ---_______---

**提前致谢!!!

因为我没有完整的代码,所以我不能确定,但​​是在你有 else if (e.keyCode == "37") 的地方,else 关键字会阻止在按住 jump 的同时左右移动。 此外,我建议有一个常量循环来处理移动而不是按键事件。

window.addEventListener("keydown", checkKeyPressed, false);
window.addEventListener("keyup", keyUp, false);
var jumpStarted = false;
var moveLeft = false;
var moveRight = false;
setInterval(function(){
    if(leftDown === true)
        //move Left
    else if(rightDown === true)
        //move Left
    if(jumpStarted)
        //Jump code
}, 10);
   function checkKeyPressed(e) {

        if (e.keyCode == "38" && jumpTime == 0) {
            jumpStarted = true;
        }if (e.keyCode == "37") {
            moveLeft = true;
        }else if (e.keyCode == "39") {
            moveRight = true;
        }
    }
    function keyUp(e){
        if (e.keyCode == "37") {
            moveLeft = false;
        }else if (e.keyCode == "39") {
            moveRight = false;
        }
    }

这样做的好处是,您在按下按键的整个过程中都在移动,而不仅仅是在按下按键时。它还将相关代码组合在一起。

我不是很容易理解你的代码,我决定从头开始写一些东西,希望它能有所帮助。您可能也对这个答案感兴趣:https://gamedev.stackexchange.com/a/29618/34073, and the related demo: http://jsfiddle.net/LyM87/.

// ex: if pressed[39] == true, walk to the right

var pressed = [];

// keyboard mapping

var keys = {
  JUMP: 38, 
  RIGHT: 39, 
  LEFT: 37
};

// states of the black pixel

var pixor = {
  el: $('#pixor'),
  isJumping: false,
  x: 10,
  y: 0,
  vy: 0,
  vx: 0
}

// record user keystrokes

$(document).on('keydown keyup', function (e) {
  pressed[e.which] = e.type === 'keydown';
  e.preventDefault();
});

// classical game loop: update, render, redo after 1/60 sec

function loop () {
  update();
  render();
  setTimeout(loop, 17);
}

// updates the states of the black pixel

function update () {
  
  // vertical moves
  
  if (!pixor.isJumping && pressed[keys.JUMP]) {
    pixor.isJumping = true;
    pixor.vy = 10;
  }
  if (pixor.isJumping) {
    pixor.y += pixor.vy;
    if (pixor.vy >= 0 && pixor.vy <= 0.5) {
      pixor.vy = -0.5;
    }
    if (pixor.vy > 0) {
      pixor.vy /= 1.25;
    }
    else {
      pixor.vy *= 1.25;
    }
    if (pixor.y <= 0) {
      pixor.isJumping = false;
      pixor.y = 0;
      pixor.vy = 0;
    }
  }
  
  // horizontal moves
  
  if (pressed[keys.RIGHT]) {
    pixor.vx = 5;
  }
  else if (pressed[keys.LEFT]) {
    pixor.vx = -5;
  }
  else {
    pixor.vx = 0;
  }
  pixor.x += pixor.vx;
}

// repaints the screen based on the states of the black pixel

function render () {
  pixor.el.css({
    bottom: pixor.y,
    left: pixor.x
  });
}
body {
  overflow: hidden;
}

#pixor {
  position: absolute;
  width: 40px;
  height: 40px;
  bottom: 0px;
  left: 10px;
  background: black;
}

#calltoaction {
  position: absolute;
  top: 0; right: 0; 
  bottom: 0; left: 0;
  background: rgba(0,0,0,.5);
  color: white;
  text-align: center;
  vertical-align: middle;
  font: bold 24px Arial;
}

#calltoaction:after {
  content: " ";
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pixor"></div>
<div id="calltoaction" onclick="$(this).remove();loop()">
  Click here to start, then use UP, LEFT and RIGHT.
</div>