1
votes

I've looked for help of first player rotation on three.js for a while but most of the answers are outdated with functions which currently don't exist in the updated library.

I'm trying to make my code run so that the camera will rotate around it's own axis according to the position of the mouse on the screen.

The current rotation code is:

var scale = 10;

function viewKeys(){
  document.addEventListener("mousemove", MouseMove, true);
  function MouseMove(event) {
    mouseX = event.clientX - divOffsetWidth;
    mouseY = event.clientY - divOffsetHeight;
  }
}

divOffset variables make the mouse positions read relative to the center of the HTML div.

function viewAnimate(){
  camera.rotation.x = -((3/2)*(Math.PI*mouseY)) / (scale);
  camera.rotation.y = -(2*(Math.PI*mouseX)) / (scale);
}

The viewKeys() function is called in the init() function and the viewAnimate() function is called within the animate() function.

Currently the code can rotate normally when the camera's position is (0,0,0) but if I move to a different position it looks as if the camera is rotating relative to the whole environment's axis. I am aware that there are lots of control librarys for three.js but I would like to understand how to be able to rotate something on its own axis myself.

How do you suppose I change the rotation so that it works correctly?

1

1 Answers

2
votes

If you want to rotate the camera yourself via the mouse, you will have to understand how Euler rotations work in three.js. See this answer.

One way to implement what you want is by using a pattern like so:

var scale = 1;
var mouseX = 0;
var mouseY = 0;

camera.rotation.order = "YXZ"; // this is not the default

document.addEventListener( "mousemove", mouseMove, false );

function mouseMove( event ) {

    mouseX = - ( event.clientX / renderer.domElement.clientWidth ) * 2 + 1;
    mouseY = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;

    camera.rotation.x = mouseY / scale;
    camera.rotation.y = mouseX / scale;

}

I agree with you that experimenting with this would be a good learning experience.

three.js r.89