第二个键被按下后字符停止 [英] character stops after second key pressed is lifted

查看:219
本文介绍了第二个键被按下后字符停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从箭头键接受输入,并在JavaScript中在2D画布游戏上相应地移动字符。

I'm taking input from the arrow keys and moving a character accordingly on a 2D canvas game in JavaScript.

当我按两个键,我想要特殊的东西发生像对角线移动和停止。

When I press two keys, I want special things to happen like moving diagonally and stopping.

这些特殊的事情发生,但是我抬起第二个键被按下时有一个小故障:我的角色停止移动。这不会发生,但是,如果我提起第一个按键并按住第二个键。在这种情况下,我的性格继续朝那个方向。为什么会出现这种情况?

These special things do happen, however there is a glitch when I lift up the second key that was pressed down: my character stops moving. This doesn't happen, though, if I lift the first key pressed and keep the second key pressed. In that case, my character continues in that direction. Why does this occur??

以下是此函数的代码片段:

//both up and down keys pressed, character should stop
if(Keys.up && Keys.down){
    character.y -= 10;
    character.y += 10;
}
else if(Keys.down){
    character.y += 10;
}
else if(Keys.up){
    character.y -= 10;
}



此外,我从 onkeydown onkeyup 事件并将它们存储在一个名为Keys的对象中。 (例如 Keys [e.keyCode] = true)
当按下该键时,该键的布尔值为true。

Also, I am taking the input from onkeydown and onkeyup events and storing them in an object called Keys. (e.g. Keys[e.keyCode] = true ) When the key is pressed, that key's boolean value is true. When lifted it is false.

推荐答案

要移动对角线,你需要一个x分量,而不仅仅是一个Y.因此,你需要一个

To move diagonal, you need an x component, not just a Y. So you need a listener for both x and y.

此外,为什么不直接做(而不是强迫客户端做无计算的计算):

Also, for this, why not just do (instead of forcing the client to do the calculations for no reason):

if(Keys.up && Keys.down){
    return;
}

另外,当添加X组件时,不要使用else if

Also, when you add the X component, dont use "else if" - just use "if" as you want to be able to capture more than one input at a time to move diagonally.

应该看起来像这样:

if(Keys.up && Keys.down){
    return;
}
if(Keys.down){
    character.y += 10;
}
if(Keys.up){
    character.y -= 10;
}
if(Keys.left){
    character.x -= 10;
}
if(Keys.right){
    character.x += 10;
}

您也可以使用CSS动画在位置之间移动,使运动更平滑(每个按钮按下时不跳动10px)。

You can also do interpolation using CSS animation to move between the positions in order to make the movement smoother (and not jump 10px each button press).

这篇关于第二个键被按下后字符停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆