[英]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事件仅开始移动,然后继续在循环(
setInterval
或requestAnimationFrame
)内移动角色,直到发生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.