我有一个简单的Three.js场景,在其中生成了一些网格。 其中一些具有名称属性='quadrant'。 我只想以任何方式获取所有名为“ quadrant”的网格物体。 我使用了 scene.getObjectByName(“ quadrant”); ,它可以工作,但只返回找到的第一个名为“ quadrant”的元素。我该怎么办?
答案 0 :(得分:0)
我也做了一些挖掘工作来为自己澄清这一点。因此,长话短说,您将无法使用getObjectByName
方法访问所有网格。它不像CSS中的类选择器那样工作。
Three.JS文档指出:
.getObjectByName(name:String)- 搜索对象的子项,并返回第一个具有匹配名称的子项。
因此,您有2个选择:
我制作了带有动画和材质修改的代码段,因为不清楚您要实现什么。
示例包含:
getObjectByName
方法对一个对象进行修改所以,简而言之:
scene.traverse(function(child) {
if (child.name === "quadrant") {
child.material = ClassMaterial; //apply same material to all meshes
}
});
希望解决方案明确,祝你好运。
更详细的示例:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 50;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var UniceMaterial = new THREE.MeshBasicMaterial({
color: 0xffff00
});
var ClassMaterial = new THREE.MeshBasicMaterial({
color: 0x00ffff
});
for (j = 0; j < 10; j++) {
var cube = new THREE.Mesh(geometry, material);
cube.name = "demo";
cube.myid = j;
cube.position.x = j * -2;
cube.position.y = j - 2;
cube.position.z = j / 100;
scene.add(cube);
}
for (i = 0; i < 10; i++) {
var cube = new THREE.Mesh(geometry, material);
cube.name = "quadrant";
cube.myid = i;
cube.position.x = i * 2;
cube.position.y = i + 2;
cube.position.z = i / 100;
scene.add(cube);
}
for (i = 0; i < 4; i++) {
var cube = new THREE.Mesh(geometry, material);
cube.name = "quadrant" + 1;
cube.myid = i;
cube.position.x = 0;
cube.position.y = i * -4;
cube.position.z = i / 100;
scene.add(cube);
}
scene.traverse(function(child) {
//if (child instanceof THREE.Mesh) {
if (child.name === "quadrant") {
child.material = ClassMaterial;
//console.log (child);
}
//child.material = ClassMaterial;
//}
});
ObjectWithGetMethod = scene.getObjectByName("quadrant1");
ObjectWithGetMethod.material = UniceMaterial;
var animate = function() {
requestAnimationFrame(animate);
scene.traverse(function(cube) {
if (cube.name === "demo") {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
}
});
//despite you try to select "quadrant" it animates last added cube:
if (cube.name = "quadrant") {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
}
renderer.render(scene, camera);
};
animate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/90/three.min.js"></script>
<html>
<head>
<title>My first three.js app</title>
<style>
body {
margin: 0;
}
canvas {
width: 100%;
height: 100%
}
</style>
</head>
<body>
</body>
</html>