Home > Web Front-end > JS Tutorial > Detailed explanation of Three.js sample code for obtaining the three-dimensional coordinates of mouse click

Detailed explanation of Three.js sample code for obtaining the three-dimensional coordinates of mouse click

黄舟
Release: 2017-03-25 14:28:30
Original
2584 people have browsed it

This article mainly introduces the Three.js sample code for obtaining the three-dimensional coordinates of mouse clicks. It has certain reference value, and interested friends can refer to it.

Due to work needs, but I don’t know anything about three.js, and there is very little information on the Internet, so I was asked to get the coordinates. It was really a big deal. At any rate, it finally came true.

Now that you want to get the three-dimensional coordinates of the mouse click, I believe you already have the cameraobject and scene. If you don’t know, you can check it out first. Take a look at these two objects. Here we mainly talk about how to obtain three-dimensional coordinates, leaving aside the principles. Above code:

function onDocumentMouseDown( event ) {
  event.preventDefault();
  var vector = new THREE.Vector3();//三维坐标对象
  vector.set(
    ( event.clientX / window.innerWidth ) * 2 - 1,
    - ( event.clientY / window.innerHeight ) * 2 + 1,
    0.5 );
  vector.unproject( camera );
  var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
  var intersects = raycaster.intersectObjects(scene.children);
  if (intersects.length > 0) {
    var selected = intersects[0];//取第一个物体
    console.log("x坐标:"+selected.point.x);
    console.log("y坐标:"+selected.point.y);
    console.log("z坐标:"+selected.point.z);
  }
Copy after login

What I understand is that when the mouse is clicked, the screen receives two-dimensional coordinates. This two-dimensional coordinate is connected to the camera and extends in the direction of the viewing angle to form a ray. This ray It will intersect with the objects in the scene and receive all the objects that intersect. The first object is the one closest to the camera, and the last one is the one farthest from the camera. Generally, the first intersecting object is used as the object clicked by the mouse.


The above is the detailed content of Detailed explanation of Three.js sample code for obtaining the three-dimensional coordinates of mouse click. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template