0

I'm making a platformer HTML game and have a problem that the player doesn't instantly move after I trigger the touch event. When I start pressing the button I have to wait 1-2 seconds till the player starts moving

I've also had other games with the same problem where I tried other methods fixing it.

Here's the code:

<div id="stage">
    <div id="player"></div>
    <div id="block"></div>
    <button ontouchstart="config.speedX = -1" ontouchend="config.speedX = 0" id="left"></button>
    <button ontouchstart="config.speedX = 1" ontouchend="config.speedX = 0" id="right"></button>
</div>
let config = {
    x: 0,
    y: 0,
    speedX: 0,
    speedY: 0
};

let gameloop = setInterval(() => {
    player.style.left = config.x + "px";
    player.style.bottom = config.y + "px";
    config.x += config.speedX;
    config.y += config.speedY;
}, 20);
M0nst3R
  • 5,186
  • 1
  • 23
  • 36
  • What happens if you change it from a ` – Samathingamajig Jul 14 '23 at 18:13
  • Well, it's got to wait at least 20 ms for the loop to run before it picks up on the change. Also ` – Heretic Monkey Jul 14 '23 at 18:15
  • @Samathingamajig That does nothing – samuraiskiy Jul 14 '23 at 18:20
  • @HereticMonkey The 20ms timeout isn't really the case, in one of my other games I had a lower timeout and still the same touch event delay – samuraiskiy Jul 14 '23 at 18:35
  • i think you need to add `sleep()`, check this for how to use https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – QuantumX Jul 14 '23 at 20:32

0 Answers0