【发布时间】:2021-12-19 02:26:21
【问题描述】:
我想在three.js中通过该对象的特定顶点来更改对象的位置。我有这个 .OBJ glasses model 有 8,856 vertices。这是我的代码:
注意:OBJLoader.js 是必需的。
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vertices Positioning</title>
</head>
<body>
<canvas
id="modelCanvas"
width="600px"
height="400px"
></canvas>
</body>
<!-- JavaScript -->
<script src="js/three.js"></script>
<script src="js/OBJLoader.js"></script>
<script src="script.js"></script>
</html>
script.js:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 600 / 400, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
canvas: modelCanvas,
});
renderer.setSize(600, 400);
renderer.setClearColor(0x000000, 0);
document.body.appendChild(renderer.domElement);
const loader = new THREE.OBJLoader();
let obj3D = new THREE.Object3D();
loader.load(
"./model.obj",
function (obj) {
obj3D = obj;
console.log(obj3D);
scene.add(obj3D);
}
);
camera.position.z = 5;
const render = function () {
requestAnimationFrame(render);
renderer.render(scene, camera);
};
render();
我的意思是,假设对象位于其default location of 0, 0(红点:默认位置,青色点:顶点位置)。现在,如果我想获取特定顶点的位置(左上角)和change the vertex's position,对象的位置也会发生变化(青色点:对象位置,蓝点:新顶点位置)。这就是我想在 Three.js 中实现的目标。
奖励:
我做了一些研究,发现顶点位于 Object3D > Children > (Index of the Mesh) > geometry > attributes, check this image。这包含法线、位置和紫外线。它们中的每一个都包含一个顶点数组。但是这个数组只包含一个位置编号,所以不知道是X轴,Y轴还是Z轴。
感谢您的帮助!
【问题讨论】:
-
position属性数组中的每个三元组数字定义了一个具有各自 x、y、z 坐标的顶点。 -
不,
position属性包含 triplets,如下所示:[ x1, y1, z1, x2, y2, z2, ... ]。因此,要制作第一个顶点的Vector3,您可以执行以下操作:let v = new THREE.Vector3(mesh.geometry.attributes.position.array[ 0 ], mesh.geometry.attributes.position.array[ 1 ], mesh.geometry.attributes.position.array[ 2 ]); -
@TheJim01 很好,但是如何更改位置?因为
v.x/y/z = position不起作用,因为我们正在创建一个新向量。 -
@TheJim01 谢谢!将此作为答案发布,我会将其标记为已解决。
标签: javascript three.js position vertex