O'Reilly logo

Game Development with Three.js by Isaac Sukin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Clicking

Clicking on the screen in order to select or interact with something is a common requirement, but it's somewhat harder than it sounds because of the need to project the location of the click in the 2D plane of your screen into the 3D world of Three.js. To do this, we draw an imaginary line, called a ray, from the camera toward the position where the mouse might be in 3D space and see if it intersects with anything.

In order to project, we first need a projector:

projector = new THREE.Projector();

Then we need to register a listener on the click event for the canvas:

renderer.domElement.addEventListener('mousedown', function(event) { var vector = new THREE.Vector3( renderer.devicePixelRatio * (event.pageX - this.offsetLeft) / this.width * ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required