user3669481
user3669481

Reputation: 327

Change object rotating animation direction based on keyboard threejs

I am able to change the object rotation direction by setting up the key control using:

 case 37:
      scene.rotation.x -= 0.01;
      break
 case 38:
      scene.rotation.z -= 0.01
      break

but the rotation here is discrete, meaning that if I stop pressing the keyboard, my scene will stop rotating as well. I know I can set up requestAnimationFrame in the render function and specify a rotation direction to make an animation. How can I change the rotation direction based on keyboard input and still keep the animation going?

Upvotes: 0

Views: 745

Answers (1)

stdob--
stdob--

Reputation: 29172

0) It is necessary to store the rotational speed of the object:

mesh.rotSpeed = { x: 0, y: 0};

1) By clicking on the arrows necessary to change the rotation speed about a respective axis:

switch (e.keyCode){
    case 37:
      mesh.rotSpeed.x += 0.01;
      break;
    case 39:
      mesh.rotSpeed.x -= 0.01;
      break;               
    case 38:
      mesh.rotSpeed.y +=0.01;
      break;
    case 40:
      mesh.rotSpeed.y -=0.01;
      break;                
}

2) In the animation cycle to rotate the object about the axes with the desired speed:

mesh.rotation.x += mesh.rotSpeed.x;
mesh.rotation.y += mesh.rotSpeed.y;

JSFiddle

Upvotes: 1

Related Questions