Hi everyone,
I’m justing getting started with three.js and practicing on the cube.
I would like to ask for help for my problem. Basically, it has two things:
- Cube has to rotate following mouse’s movement
- Cube only rotate horizontally and vertically in limited angles
Currently, I can limit the angle of rotation but the cube is not following the mouse. A similar thing is that when I’m able to make cube rotating on mousemove, then the angles are not limited.
#For onmouse event: i used LookAt on an Object3D
#For rotating angle limit: i used OrbitControls
Could you help me review the code below:
//SCENE
let scene = new THREE.Scene();
//CAMERA
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1,
1000);
camera.position.set(7, 3.5, 7)
const myCanvas = document.querySelector(".myCanvas");
//RENDER
const renderer = new THREE.WebGLRenderer({ antialias: true, canvas: myCanvas, alpha: true,
physicallyCorrectLights: true });
//LOADER
let base = new THREE.Object3D();
const gltf = new GLTFLoader().setPath('/assets/images/work/2022_s2w_pic/3d/');
gltf.load('scene.gltf', function (gltf) {
const model = gltf.scene;
model.scale.setScalar(3);
model.traverse(function (object) {
if (object.isMesh) {
object.castShadow = true;
object.geometry.center();
}
})
base.add(model);
render();
}, undefined, function (error) {
console.error(error);
})
//CONTROLS
const controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', render);
controls.minDistance = 2;
controls.maxDistance = 10;
controls.target.set(0, 0, 0);
controls.enableZoom = false;
controls.maxPolarAngle = Math.PI * 0.44;
controls.minPolarAngle = Math.PI * 0.30;
controls.minAzimuthAngle = Math.PI * 0.18;
controls.maxAzimuthAngle = Math.PI * 0.33;
controls.enablePan = false;
controls.update();
//MOUSE
let mouse = new THREE.Vector2();
let plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -2);
let raycaster = new THREE.Raycaster();
let pointOfIntersection = new THREE.Vector3();
scene.add(base);
myCanvas.addEventListener(‘mousemove’, onMouseMove, false);
function animate() {
requestAnimationFrame(animate);
raycaster.setFromCamera(mouse, camera);
controls.update();
renderer.render(scene, camera);
}
function onMouseMove(event) {
// calculate mouse position in normalized device coordinates
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.ray.intersectPlane(plane, pointOfIntersection);
base.lookAt(pointOfIntersection);
}
function render() {
renderer.render(scene, camera);
}
animate();