Working with Sprite Maps
Learn how to create a 2D heads-up display (HUD) using maps in Three.js.
We'll cover the following...
Sprite maps
We can use sprites to create a simple 2D heads-up display (HUD) on top of an existing scene. We used a THREE.Sprite
object to render single points. These sprites were positioned somewhere in the 3D world, and their size was based on the distance from the camera (this is also sometimes called billboarding). In this lesson, we’ll show an alternative use of the THREE.Sprite
object: we’ll show how we can use THREE.Sprite
to create a layer similar to a HUD for our 3D content using an extra THREE.OrthographicCamera
instance and an additional THREE.Scene
. We will also show how to select the image for a THREE.Sprite
object using a sprite map.
Example: Sprite map
As an example, we’re going to create a simple THREE.Sprite
object that moves from left to right over the screen. In the background, we’ll render a 3D scene with a camera, which we can move to illustrate that the THREE.Sprite
object moves independently of the camera. The following illustration shows what we’ll be creating for the first example:
Let’s execute the spritemap.js
example in the playground below by clicking 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-7': './samples/chapters/chapter-7/spritemap.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', } }