1. 从零搭建智慧仓库3D场景的基础框架
第一次用Three.js做智慧仓库项目时,我盯着空白的浏览器窗口发呆了半小时——3D场景开发就像装修毛坯房,得先打好地基。我们先来创建最基础的场景结构:
javascript复制// 初始化场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
这里有个新手容易踩的坑:相机位置不设置的话,你会看到一个黑屏。建议初始化时就把相机往后拉:
javascript复制camera.position.z = 50;
camera.position.y = 30;
camera.lookAt(0, 0, 0); // 让相机看向场景中心
别忘了添加光源,否则所有物体都是黑的。我习惯用环境光+平行光的组合:
javascript复制const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(10, 20, 10);
scene.add(directionalLight);
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 构建仓库的地面与墙体系统
2.1 智能地板生成方案
仓库地板绝不是简单的一个平面,要考虑纹理重复、阴影接收等细节。这是我优化后的地板生成代码:
javascript复制function createFloor(width, depth) {
const geometry = new THREE.BoxGeometry(width, 1, depth);
const texture = new THREE.TextureLoader().load('floor_texture.jpg');
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(width/10, depth/10); // 按实际尺寸自动计算重复次数
const material = new THREE.MeshStandardMaterial({
map: texture,
roughness: 0.8
});
const floor = new THREE.Mesh(geometry, material);
floor.receiveShadow = true; // 关键!允许接收阴影
floor.position.y = -0.5; // 让地板顶部正好在y=0平面
return floor;
}
实用技巧:如果发现纹理模糊,记得设置纹理的anisotropy属性:
javascript复制texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
2.2 参数化墙体建造
四面墙的创建可以封装成智能函数,这是我项目中使用的方案:
javascript复制function createWalls(roomWidth, roomDepth, height) {
const walls = [];
const materials = [
new THREE.MeshStandardMaterial({ color: 0xafc0ca }), // 前
new THREE.MeshStandardMaterial({ color: 0x9cb2d1 }), // 后
new THREE.MeshStandardMaterial({ color: 0xd6e4ec }), // 左右
];
// 前后墙
walls.push(createWall(roomWidth, height, 0.2,
[0, heigh
