Wanderson Silva
Wanderson Silva

Reputation: 1199

Rotate Three.js scene on mouse move

I have a scene redered just fine and need to make it rotate horizontally and/or vertically as the mouse moves over the DOM. I was able to do the horizontal rotation by changind the scene rotation.y property:

const step = 0.005;

let halfWindowWidth = window.innerWidth / 2;
let target = (Math.PI / halfWindowWidth * mouseX / 2) - 0.785398;

if (target < y) {
    if (y - (step * 2) > target) {
        target = y - (step * 2);
    }
} else if (target > y) {
    if (y + (step * 2) < target) {
        target = y + (step * 2);
    }
}

scene.rotation.y = target;

I know that maybe I will need to work on the x and z axis to make it rotate vertically, but I don't know what calculations should I do.

The rotation must take place as the mouse goes further from the center of the DOM, from -90˚ to 90˚ (180˚ in total). The step constant I use to have the rotation be animated and not simply jump when the mouse moves too quick.

Upvotes: 0

Views: 3151

Answers (1)

Darshit Hedpara
Darshit Hedpara

Reputation: 670

Take a look at the following examples

http://threejs.org/examples/#misc_controls_orbit http://threejs.org/examples/#misc_controls_trackball

there are other examples for different mouse controls, but both of these allow the camera to rotate around a point and zoom in and out with the mouse wheel, the main difference is OrbitControls enforces the camera up direction, and TrackballControls allows the camera to rotate upside-down.

All you have to do is include the controls in your html document

<script src="js/OrbitControls.js"></script>

and include this line in your source

controls = new THREE.OrbitControls( camera, renderer.domElement );

Upvotes: 1

Related Questions