BabylonJS - 贴花
Babylon.js - 贴花
Section titled “Babylon.js - 贴花”贴花 (Decals) 就像是将贴纸或纹理投射到网格 (mesh) 的表面上。想象一下子弹击中墙壁时出现的弹孔,或者角色在雪地上行走时留下的脚印。贴花允许您动态地将这些视觉细节添加到现有几何体上,而无需修改底层网格结构。
在 Babylon.js 中,您可以使用 BABYLON.MeshBuilder.CreateDecal 创建贴花。此方法将纹理(由材质定义)投射到目标网格上的特定位置和方向(通常由射线投射 (raycast) 命中点确定)。
基本语法包括指定名称、目标网格、位置、法线 (方向)、贴花的大小,以及可选的角度。
import * as BABYLON from '@babylonjs/core';
// Assuming 'targetMesh', 'pickInfo' (from scene.pick), 'decalMaterial' are defined// 假设 'targetMesh'、'pickInfo'(来自 scene.pick)和 'decalMaterial' 已定义
// pickInfo contains details about where the user clicked on the mesh// pickInfo 包含用户在网格上点击位置的详细信息const 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;}decalMaterial 通常是 StandardMaterial 或 PBRMaterial,其 diffuseTexture 带有用于透明度的 alpha 通道(例如,带有透明背景的弹孔 PNG 图像)。在材质上设置 zOffset 可以帮助防止Z-fighting (深度冲突) 问题,即贴花与底层网格表面之间发生闪烁。
// Example Decal Material Setup// 贴花材质设置示例const decalMaterial = new BABYLON.StandardMaterial("decalMat", scene);decalMaterial.diffuseTexture = new BABYLON.Texture("textures/impact.png", scene); // PNG with alpha// 带有 alpha 通道的 PNGdecalMaterial.diffuseTexture.hasAlpha = true;decalMaterial.zOffset = -2; // Push the decal slightly into the surface// 将贴花稍微推入表面decalMaterial.specularColor = new BABYLON.Color3(0, 0, 0); // Often decals shouldn't be shiny// 贴花通常不应该反光此示例加载一个 glTF 模型,并允许用户点击它来放置撞击贴花。
<!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) // 加载模型(请替换为您的 glTF/glb 文件) // 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 --- // --- 取消注释以加载 glTF 模型 --- try { const result = await BABYLON.SceneLoader.ImportMeshAsync("", "path/to/your/model/", "yourModel.glb", scene); // path/to/your/model/ 应替换为模型文件所在的路径 // yourModel.glb 应替换为您的模型文件名 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 // 确保 'textures/impact.png' 存在并且正确提供服务 decalMaterial.diffuseTexture = new BABYLON.Texture("textures/impact.png", scene); decalMaterial.diffuseTexture.hasAlpha = true; decalMaterial.useAlphaFromDiffuseTexture = true; // Ensure alpha is used // 确保使用了 alpha 通道 console.log("Decal texture loaded."); // 贴花纹理加载成功。 } catch (texError) { console.warn("Could not load decal texture 'textures/impact.png'. Using solid color instead.", texError); // 无法加载贴花纹理 'textures/impact.png'。改用纯色。 }
// 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 // 5 秒后消失 } } });
return scene; };
createScene().then(sceneToRender => { engine.runRenderLoop(function () { if (sceneToRender) { sceneToRender.render(); } }); });
window.addEventListener("resize", function () { engine.resize(); }); </script></body></html>为了使演示完全运行,您需要在 HTML 文件相对路径下的 textures 文件夹中有一个名为 impact.png 的图像文件(最好带有透明度)。您可以将其替换为任何图像。如果您取消注释 SceneLoader 部分,您还需要在指定路径下有一个 yourModel.glb 文件。
场景将显示一个 3D 对象(可以是球体或您加载的模型)。当您在对象上左键点击时,一个小的贴花(代表撞击标记,使用 impact.png 纹理或在纹理加载失败时使用纯红色)将出现在点击位置的表面上。这些贴花将具有随机旋转,并会在 5 秒后自动消失。