测试平台:https://playground.babylonjs.com/?BabylonToolkit#CJNZRE#3
测试效果:
测试代码:
// 更新 DOM 元素的位置
function updateIndicatorPosition(camera,mesh,indicator) {
var meshPosition = mesh.getBoundingInfo().boundingBox.centerWorld;
var projectedPosition = BABYLON.Vector3.Project(
meshPosition,
BABYLON.Matrix.Identity(),
scene.getTransformMatrix(),
camera.viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight())
);
const canvas = document.getElementById('renderCanvas');
// 获取 canvas 元素的边界框信息
const rect = canvas.getBoundingClientRect();
// 将投影的坐标转换为屏幕坐标
indicator.style.left = (rect.left+projectedPosition.x - 10) + "px"; // -10 是为了将指示器中心对准 mesh
indicator.style.top = (rect.top+projectedPosition.y - 10) + "px"; // -10 是为了将指示器中心对准 mesh
}
var createScene = function () {
// This creates a basic Babylon Scene object (non-mesh)
var scene = new BABYLON.Scene(engine);
// This creates and positions a free camera (non-mesh)
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
// This targets the camera to scene origin
camera.setTarget(BABYLON.Vector3.Zero());
// This attaches the camera to the canvas
camera.attachControl(canvas, true);
// 创建一个 DOM 元素来指示 mesh 的位置
var indicator = document.createElement("div");
indicator.style.position = "absolute";
indicator.style.width = "20px";
indicator.style.height = "20px";
indicator.style.backgroundColor = "red";
document.body.appendChild(indicator);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
// Default intensity is 1. Let's dim the light a small amount
light.intensity = 0.7;
// Our built-in 'sphere' shape.
var sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter: 2, segments: 32}, scene);
// Move the sphere upward 1/2 its height
sphere.position.y = 1;
// Our built-in 'ground' shape.
var ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 6, height: 6}, scene);
engine.runRenderLoop(function() {
scene.render();
updateIndicatorPosition(camera,sphere,indicator);
});
return scene;
};