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
Also, velX and velY are velocity, and posX and posY are positions for my character.
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.
Something like this (the animation is maybe crude, but works as PoC): https://codepen.io/anon/pen/VRgNrQ
您是否尝试过按键...按键是邪恶的
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.