BabylonJS - Decals
Babylon.js - Decals
Section titled “Babylon.js - Decals”Decals are like projecting stickers or textures onto the surface of a mesh. Imagine bullet holes appearing on a wall where shots land, or footprints appearing on snow as a character walks. Decals allow you to dynamically add these visual details to existing geometry without modifying the underlying mesh structure.
In Babylon.js, you create decals using BABYLON.MeshBuilder.CreateDecal. This method projects a texture (defined by a material) onto a target mesh at a specific position and orientation (usually determined by a raycast hit).
Creating a Decal
Section titled “Creating a Decal”The basic syntax involves specifying a name, the target mesh, the position, normal (direction), size of the decal, and optionally an angle.
import * as BABYLON from '@babylonjs/core';
// Assuming 'targetMesh', 'pickInfo' (from scene.pick), 'decalMaterial' are defined
// pickInfo contains details about where the user clicked on the meshconst pickResult = scene.pick(scene.pointerX, scene.pointerY);
if (pickResult.hit && pickResult.pickedMesh === targetMesh) { const decalPosition = pickResult.pickedPoint; // Where the decal should be placed const decalNormal = pickResult.getNormal(true); // The surface direction at the hit point const decalSize = new BABYLON.Vector3(1, 1, 1); // Size of the decal projection box const angle = Math.random() * Math.PI * 2; // Optional: Random rotation
const newDecal = BABYLON.MeshBuilder.CreateDecal( "decal", // Name targetMesh, // Mesh to receive the decal { position: decalPosition, normal: decalNormal, size: decalSize, angle: angle } );
// Apply a material to the decal (often a texture with transparency) newDecal.material = decalMaterial;}The decalMaterial is typically a StandardMaterial or PBRMaterial with a diffuseTexture that has an alpha channel for transparency (e.g., a PNG image of a bullet hole with a transparent background). Setting zOffset on the material can help prevent z-fighting issues where the decal flickers with the underlying mesh surface.
// Example Decal Material Setupconst decalMaterial = new BABYLON.StandardMaterial("decalMat", scene);decalMaterial.diffuseTexture = new BABYLON.Texture("textures/impact.png", scene); // PNG with alphadecalMaterial.diffuseTexture.hasAlpha = true;decalMaterial.zOffset = -2; // Push the decal slightly into the surfacedecalMaterial.specularColor = new BABYLON.Color3(0, 0, 0); // Often decals shouldn't be shinyThis example loads a glTF model and allows the user to click on it to place impact decals.
<!DOCTYPE html><html><head> <meta charset="utf-8"/> <title>Babylon.js - Decal Demo</title> <script src="https://cdn.babylonjs.com/babylon.js"></script> <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script> <style> html, body { overflow: hidden; width: 100%; height: 100%; margin: 0; padding: 0; } #renderCanvas { width: 100%; height: 100%; touch-action: none; } </style></head><body> <canvas id="renderCanvas"></canvas> <script type="text/javascript"> const canvas = document.getElementById("renderCanvas"); const engine = new BABYLON.Engine(canvas, true);
const createScene = async function () { const scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color4(0.1, 0.1, 0.15, 1.0);
const camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI / 2, Math.PI / 2.5, 3, new BABYLON.Vector3(0, 1, 0), scene); camera.attachControl(canvas, true); camera.wheelPrecision = 50; camera.minZ = 0.1;
const light = new BABYLON.HemisphericLight("HemiLight", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.8;
// Load a model (replace with your own glTF/glb file) // Example using a simple sphere if no model is available let targetMesh = BABYLON.MeshBuilder.CreateSphere("targetSphere", {diameter: 2, segments: 32}, scene); targetMesh.position.y = 1; /* // --- Uncomment to load a glTF model --- try { const result = await BABYLON.SceneLoader.ImportMeshAsync("", "path/to/your/model/", "yourModel.glb", scene); if (result.meshes.length > 0) { targetMesh = result.meshes[0]; // Assuming the first mesh is the target camera.target = targetMesh.position; console.log("Model loaded successfully!"); } else { console.error("No meshes found in the loaded model."); } } catch (error) { console.error("Error loading model:", error); // Keep the fallback sphere if loading fails } // -------------------------------------- */
// Decal Material Setup const decalMaterial = new BABYLON.StandardMaterial("decalMat", scene); // Use a placeholder color if texture loading fails or is omitted decalMaterial.diffuseColor = new BABYLON.Color3(1, 0, 0); // Red color for visibility decalMaterial.zOffset = -2; decalMaterial.specularColor = new BABYLON.Color3(0, 0, 0); try { // Make sure 'textures/impact.png' exists and is served correctly decalMaterial.diffuseTexture = new BABYLON.Texture("textures/impact.png", scene); decalMaterial.diffuseTexture.hasAlpha = true; decalMaterial.useAlphaFromDiffuseTexture = true; // Ensure alpha is used console.log("Decal texture loaded."); } catch (texError) { console.warn("Could not load decal texture 'textures/impact.png'. Using solid color instead.", texError); }
// Pointer Observable for Clicks scene.onPointerObservable.add((pointerInfo) => { if (pointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN && pointerInfo.event.button === 0) { // Left mouse button
const pickResult = scene.pick(scene.pointerX, scene.pointerY);
if (pickResult.hit && pickResult.pickedMesh === targetMesh) { const decalSize = new BABYLON.Vector3(0.2, 0.2, 0.2); // Adjust size as needed const newDecal = BABYLON.MeshBuilder.CreateDecal("decal", targetMesh, { position: pickResult.pickedPoint, normal: pickResult.getNormal(true), size: decalSize, angle: Math.random() * Math.PI * 2 }); newDecal.material = decalMaterial;
// Optional: Make decals disappear after some time setTimeout(() => { if (newDecal) { newDecal.dispose(); } }, 5000); // Disappear after 5 seconds } } });
return scene; };
createScene().then(sceneToRender => { engine.runRenderLoop(function () { if (sceneToRender) { sceneToRender.render(); } }); });
window.addEventListener("resize", function () { engine.resize(); }); </script></body></html>Required Assets
Section titled “Required Assets”For the demo to work fully, you need an image file named impact.png (ideally with transparency) inside a textures folder relative to your HTML file. You can replace this with any image. If you uncomment the SceneLoader part, you also need a yourModel.glb file in the specified path.
Output Description
Section titled “Output Description”The scene will show a 3D object (either a sphere or your loaded model). When you left-click on the object, a small decal (representing an impact mark, using the impact.png texture or a solid red color if the texture fails to load) will appear on the surface at the click location. The decals will have a random rotation and will automatically disappear after 5 seconds.