如何将腿固定在桌子上

问题描述 投票:0回答:1

四条腿应该是桌子的一部分,我认为不应该像添加的那样添加到场景中。

还有什么是创建新的腿实例并附加它们的好方法。并且附件应使后侧腿看起来比前侧小。目前我只看到单腿,而不是 4 条。

如果您在本地运行此代码,您就会知道我在问什么。

<script type="importmap">
{
  "imports": {
    "three": "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.163.0/three.module.min.js"
  }
}
</script>
<script type="module">
import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 10000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(8, 0.5, 4);

// Correcting texture loading
//const textureLoader = new THREE.TextureLoader();
//const texture = textureLoader.load('http://localhost:3000/wood-texture-vector-eps10-illustration-600nw-206847232.webp');
const material = new THREE.MeshBasicMaterial({
  //map: texture
  color: 0x885511 // brown?
});

const cube = new THREE.Mesh(geometry, material);


const legGeometry = new THREE.BoxGeometry(0.4, 4, 0.4);

const cubeLeg = new THREE.Mesh(legGeometry, material);



scene.add(cube);
scene.add(cubeLeg);
cubeLeg.position.x = 12;
scene.add(cubeLeg);
cubeLeg.position.x = -12;
scene.add(cubeLeg);
cubeLeg.position.x = 6;
scene.add(cubeLeg);
cubeLeg.position.x = -6;

camera.position.x = 2;
camera.position.y = 4;
camera.position.z = 13;

function animate() {
  requestAnimationFrame(animate);

  //cube.rotation.x += 0.01;
  //cube.rotation.y += 0.01;

  renderer.render(scene, camera);
}

animate();
</script>

javascript three.js
1个回答
0
投票
scene.add(cube);
scene.add(cubeLeg);
cubeLeg.position.x = 12;
scene.add(cubeLeg);
cubeLeg.position.x = -12;
scene.add(cubeLeg);
cubeLeg.position.x = 6;
scene.add(cubeLeg);
cubeLeg.position.x = -6;

这不是实例化在 Three.js 中的工作方式。

Object3D.add
(这是在
scene.add
线上被调用的)不会创建副本或实例,因此您正在一遍又一遍地添加相同的形状,并且仅更改其位置。这就是为什么你只看到一条腿。

如果您想要多条腿,可以使用

Mesh.clone
创建副本。如果您想要实例,请查看官方文档和示例以获取
InstancedMesh

要回答标题中如何“附加”它们的问题,您可以使用

Group
将所有形状收集到本地空间中。当您移动
Group
时,所有子对象(无论是
Mesh
还是更多
Group
)都会跟随父对象
Group

// basic example:
const table = new THREE.Group();
const leg1 = new Mesh(geometry, material);
const leg2 = leg1.clone();
const leg3 = leg1.clone();
const leg4 = leg1.clone();
const tableTop = new Mesh(tabletopGeometry, material);
// position all the parts, then...
table.add(tableTop, leg1, leg2, leg3, leg4);
scene.add(table);
// from here, if you reposition "table", all parts of the table will follow
© www.soinside.com 2019 - 2024. All rights reserved.