How to calculate object rotation.y in three js to look mouse pointer?
When i move mouse pointer from 1 to 2, arrow should turn to point 2. How do i calculate rotation.y?
How to calculate object rotation.y in three js to look mouse pointer?
When i move mouse pointer from 1 to 2, arrow should turn to point 2. How do i calculate rotation.y?
As an option, you can use THREE.Raycaster()
with THREE.Plane()
and use .lookAt()
of your arrow to point it at the point of intersection of the raycaster's ray and plane.
Let's create our arrow object:
var coneGeom = new THREE.ConeGeometry(0.125, 1, 4);
coneGeom.translate(0, .5, 0);
coneGeom.rotateX(Math.PI / 2); //
var coneMat = new THREE.MeshNormalMaterial();
var cone = new THREE.Mesh(coneGeom, coneMat);
cone.lookAt(new THREE.Vector3(0, 1, 0));
scene.add(cone);
then we'll add an event listener for mousemove
:
window.addEventListener("mousemove", onmousemove, false);
and then our onmousemove
function will be like this:
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0); // it's up to you how you will create THREE.Plane(), there are several methods
var raycaster = new THREE.Raycaster(); //for reuse
var mouse = new THREE.Vector2(); //for reuse
var intersectPoint = new THREE.Vector3();//for reuse
function onmousemove(event) {
//get mouse coordinates
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);//set raycaster
raycaster.ray.intersectPlane(plane, intersectPoint); // find the point of intersection
cone.lookAt(intersectPoint); // face our arrow to this point
}
jsfiddle example r86