Cube moves a bit more each time

So, I’m using three.js, and I tried to make a moving cube: W to go further, S to get closer, A to go to the left, D to go to the right, E to move up, and Q to go down, but for some reason, if you spam the keys over and over, the distance that the cube moves is bigger. That is an unwanted feature. Repl link: https://replit.com/@TheC0ders/3D-Movement-Control-Developement#script.js

When I try to use it the cube doesn’t seem to move, have you removed that code of it or is something not working? I do notice there are listeners for the keys but nothing it happening.

W moves the cube further, and S moves it closer. You can try using other keys, like Q and E, or A and D.

wasd moves the cube.

Yes. WASDQE move the cube. That is the point of it.

if you copied it from a website which i think you did you have to ask the person who put the code onto that website. I am not sure what else but why is spamming a big deal. I could not make it do that with spamming.
:confused:

1 Like

Oh well, then. I guess I’ll have to try and find another way of moving the cube.

You should change the topic from replit help to code help.

1 Like

The cube is moving and is realistic there are no problems with it that i see.
I recommend publishing it but before changing the colour of the cube.
:grinning:

1 Like

I changed it to code help HTML/CSS/JS just now.

By the way, the only part that I copy-pasted was the part that checks that a key has been pressed and the variable part within it. The IF blocks I put in myself.

You put the addEventListener inside the render() function and by that a new listener is created for each frame.
Try to set the event listener outside of the animation loop, so it’s only added once.

Also change the keypress to keydown, since keydown have better responsiveness.

// Add event listener on keydown
document.addEventListener('keydown', (event) => {
  var name = event.key;
  var code = event.code;
  // Checking which key has been pressed, and then moving the cube
  if (code === "KeyW") {
    cube.mesh.position.z -= 0.01;
  }
  if (code === "KeyS") {
    cube.mesh.position.z += 0.01;
  }
  if (code === "KeyD") {
    cube.mesh.position.x += 0.01;
  }
  if (code === "KeyA") {
    cube.mesh.position.x -= 0.01;
  }
  if (code === "KeyE") {
    cube.mesh.position.y += 0.01;
  }
  if (code === "KeyQ") {
    cube.mesh.position.y -= 0.01;
  }
}, false);

function render() {
  // Render the scene and the camera
  renderer.render(scene, camera);
  
  // Make it call the render() function about every 1/60 second
  requestAnimationFrame(render);
}

render();

I increased the value from 0.001 to 0.01 that way you make the movement more noticeable.

3 Likes

Thanks for helping out!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.