Enabling Orbit Controls
Learn how to enable zoom-in and zoom-out features and add GUI to control properties in the browser.
Using OrbitControls
in Three.js
If we try and move the scene around with our mouse, nothing much will happen. That is because we added the camera to a fixed position, and we didn’t update its position in the animate loop. We can, of course, do this in the same manner as we did to the position of the cube, but Three.js comes with several controls that allow us to easily pan around the scene and move the camera around. For this example, we’ll introduce THREE.OrbitControls
. With these controls, we can use our mouse to move the camera around the scene and look at different objects. All we need to do to get this working is create a new instance of these controls, attach them to the camera, and call the update
function from our animation loop:
const orbitControls = new OrbitControls(camera, renderer.domElement)// and the controller has a whole range of other properties we can setfunction animate() {...orbitControls.update();}
Example: Enable the orbit control
The output of the above snippet can be tested in the below playground. Click the “Run” button:
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') // const CopyWebpackPlugin = require('copy-webpack-plugin') const fs = require('fs').promises // we should search through the directories in examples, and use // the name from the files to generate the HtmlWebpackPlugin settings. module.exports = async () => { return { module: { rules: [ { test: /\.glsl$/i, use: 'raw-loader' } ] }, mode: 'development', entry: { 'chapter-1': './samples/chapters/chapter-1/getting-started.js', }, output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/', }, plugins: [ new HtmlWebpackPlugin(), ], experiments: { asyncWebAssembly: true }, devServer: { allowedHosts: 'all', host: '0.0.0.0', port: '3000', static: [ { directory: path.join(__dirname, 'assets'), publicPath: '/assets' }, { directory: path.join(__dirname, 'dist') } ] }, mode: 'development', } }
Explanation: ...