Spin a 2D Billboard in Three.js Using SpriteMaterial
In Three.js, 2D billboards are represented by Sprite
objects, which automatically rotate to always face the camera. Because
of this camera-facing behavior, attempting to rotate the
Sprite mesh itself using its rotation property
will not produce the expected spinning effect. Instead, to spin a 2D
billboard, you must manipulate the rotation property of its
underlying SpriteMaterial. This article provides a direct,
step-by-step guide on how to access and animate this property to make
your 2D sprites spin.
Understanding Sprite Rotation
A THREE.Sprite is a 3D plane that constantly aligns
itself with the camera’s view plane. Traditional 3D rotations on the X,
Y, or Z axes of the Sprite object are overridden by the
renderer to maintain this alignment.
To rotate the image mapped onto the sprite, Three.js provides a
rotation property directly on the
SpriteMaterial class. This property rotates the 2D texture
on the sprite’s face around its center point, measured in radians.
Step-by-Step Implementation
1. Create the Sprite and SpriteMaterial
First, load your texture and assign it to a
SpriteMaterial. Then, create the Sprite using
that material and add it to your scene.
// Load the texture for your billboard
const textureLoader = new THREE.TextureLoader();
const spriteMap = textureLoader.load('path/to/your-texture.png');
// Create the SpriteMaterial
const spriteMaterial = new THREE.SpriteMaterial({
map: spriteMap,
color: 0xffffff
});
// Create the Sprite mesh and add it to the scene
const sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(2, 2, 1); // Scale the billboard as needed
scene.add(sprite);2. Rotate the Material
To rotate the billboard to a static angle, modify the
rotation property of the SpriteMaterial. The
value is represented in radians (where Math.PI is a
180-degree turn).
// Rotate the billboard 45 degrees clockwise
spriteMaterial.rotation = Math.PI / 4;3. Animate the Spin in the Render Loop
To make the billboard spin continuously, increment the
rotation property of the SpriteMaterial inside
your application’s animation loop.
function animate() {
requestAnimationFrame(animate);
// Increment rotation to spin the billboard (radians per frame)
spriteMaterial.rotation += 0.02;
// Render the scene
renderer.render(scene, camera);
}
animate();Key Considerations
- Rotation Anchor: By default, the rotation anchor
point for a
SpriteMaterialis the center of the texture(0.5, 0.5). If you need to change the pivot point of the spin, you must adjust thecenterproperty of theSpriteobject (e.g.,sprite.center.set(x, y)). - Performance: Animating the
rotationproperty of aSpriteMaterialis highly efficient because the rotation calculations are handled directly during the rendering phase, allowing you to spin hundreds of billboards simultaneously without performance degradation.