简体   繁体   English

为什么我的角色动作感觉不正确?

[英]Why does my character movement not feel right?

I tried using some code to move my character in canvas, but for some reason, the movement is very rough. 我尝试使用一些代码在画布上移动角色,但由于某种原因,这种移动非常粗糙。 When I press the movement keys, the character moves a bit, and then starts moving normally. 当我按下移动键时,角色移动了一点,然后开始正常移动。 Is there any way to make the initial key press more smooth? 有什么方法可以使初始按键更加流畅? Here is the code I'm using: 这是我正在使用的代码:

var posX = 0;
var posY = 240;

var velX = 0;
var velY = 3;

document.addEventListener("keydown", function(event) {
    if (event.keyCode == "68") {
        velX = 3;
        posX += velX;
    }else if (event.keyCode == "65") {
        velX = 3;
        posX -= velX;
    }
});

Here is a live demo : https://codepen.io/Twickz/pen/WmPWae 这是一个现场演示: https : //codepen.io/Twickz/pen/WmPWae

Also, velX and velY are velocity, and posX and posY are positions for my character. 另外,velX和velY是速度,而posX和posY是我角色的位置。

I think keyboard buffer is at fault. 我认为键盘缓冲区有问题。

One solution bypassing it would be: the keydown event only starts the movement, and then you keep moving your character inside a loop ( setInterval , or requestAnimationFrame ), until keyup happens. 绕过它的一种解决方案是:keydown事件仅开始移动,然后继续在循环( setIntervalrequestAnimationFrame )内移动角色,直到发生keyup为止。

Something like this (the animation is maybe crude, but works as PoC): https://codepen.io/anon/pen/VRgNrQ 像这样的东西(动画可能是粗糙的,但可以作为PoC使用): https : //codepen.io/anon/pen/VRgNrQ

您是否尝试过按键...按键是邪恶的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的画布框的移动在点击时会增加? - Why does the movement of my canvas box increase on click? 为什么我的背景不向右移动? - Why does my background does not move to the right? 为什么我将图像的 position 设置为变量时,我的玩家移动系统不起作用? - Why does my player movement system not work when I set the position of the image to a variable? 为什么我的文本没有在我的外部分区中浮动? - Why my textes does not float right in my outer division? VUE-COMPOSITION-API:为什么 ref 对 contenteditable 没有反应 - VUE-COMPOSITION-API: why does ref not feel reactive on contenteditable 我的 useState 有问题吗? 我觉得我的 Array ReactNative 中的值并没有正确 - Is there an issue with my useState? I feel the values are not truing up right in my Array ReactNative 为什么我的js代码没有反映正确的运行时值? - why does'nt my js code reflect the right runtime value? 为什么我的 position(right) 属性在 JavaScript 中没有改变 - Why my position(right) property does not change in JavaScript 为什么我的按钮没有打印出代码并选择正确的选项? - Why does my button not print out the code and select the right option? 为什么我的 Array Push 不能以正确的方式工作? Vue - Why does my Array Pushes doesnt work the right way? Vue
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM