Understanding Points and Sprites
Learn about points and sprites in Three.js.
Sprites in Three.js
We start with an example. Let’s open the sprite.js
example in the below playground. Upon executing this example, we’ll see a minimalistic scene, containing a simple colored square:
Example: Sprite
Let’s execute the sprite.js
example in the playground by clicking the “Run” button. Once the application is running, please click the provided link to view the output in a new window.
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-7': './samples/chapters/chapter-7/sprite.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', } }
Note: We can change the properties of the object from the right control panel in the output screen.
We can use our mouse to rotate around this scene. One thing we’ll notice is that no matter how we look at the square, it will always look the same. For instance, the following screenshot shows a view of the same scene from a different position:
We can see that the sprite is still angled toward the camera, and we can’t look behind it. We can think of a sprite as a 2D plane that always faces the camera.
Creating a sprite object
If we create a sprite without any properties, they are rendered as small, white, two-dimensional squares. To create a sprite, we only need to provide a material:
const material = new THREE.SpriteMaterial({size: 0.1,color: 0xff0000})const sprite = new THREE.Sprite(material)sprite.position.copy(new THREE.Vector3(1, 1, 1))
We can configure how the sprite appears using THREE.SpriteMaterial
:
...