I have an .obj
with its .mtl
imported in my canvas, It’s a face 3d model and I want it to look at the mouse pointer as this one moves. I’m pretty close to achieve this I think. The object moves but to the other direction, so if I move my pointer up face object goes down, if I move left face goes right and so forth…
I tried to play around with mouse 2d coordinates inside the event listener function, figuring that could be the issue but I couldn’t find a solution. Can someone point me towards the issue here?
Here’s my code:
// Create a scene
const scene = new THREE.Scene();
// Create a camera
const camera = new THREE.PerspectiveCamera(
100,
window.innerWidth/window.innerHeight,
0.1,
1000
);
// Moves the camera closer/further
camera.position.set(0, 0, 20);
// Import WebGL renderer
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
// Set color and size of the renderer
renderer.setClearColor('#e5e5e5');
renderer.setSize(
window.innerWidth,
window.innerHeight
);
// Append renderer to the body element
let canvas = renderer.domElement;
document.body.appendChild(canvas);
// Resizing canvas within browser's window responsive
window.addEventListener('resize', () =>{
renderer.setSize(
window.innerWidth,
window.innerHeight
);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
// Light Setup
let light = new THREE.PointLight(0xFFFFFF, 1, 500);
light.position.set(10, 0 ,25);
scene.add(light);
let ambient = new THREE.AmbientLight(0xB1B1B1, 0.2)
scene.add(ambient);
// LOADING OBJ
let obj;
let mtlloader = new THREE.MTLLoader();
mtlloader.load(
'facciona_test.mtl',
function(materials){
materials.preload();
//Load the object
let objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(
'facciona_test.obj',
function(object){
obj = object;
object.position.z -= 290;
object.rotation.x = -50;
object.rotation.y = 550;
scene.add(object);
}
);
}
);
// MOUSE CONTROLS
let plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 1000);
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
let pointOfIntersection = new THREE.Vector3();
canvas.addEventListener("mousemove", onMouseMove, false);
function onMouseMove(event){
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
raycaster.ray.intersectPlane(plane, pointOfIntersection);
obj.lookAt(pointOfIntersection);
}
let render = function(){
requestAnimationFrame(render);
// Spinning object
// obj.rotation.y +=s 0.01;
renderer.render(scene, camera);
}
render();