三条JS画线作为对象的子对象,指向与对象或父对象无关的Vector

时间:2018-11-30 13:48:14

标签: javascript three.js

我的场景中有对象作为父级/子级。

我需要相对于(最深)Vector3对象定义一个child,该对象指向场景(look_point)中的向量。

var grandParent = new THREE.Object3D();
var parent = new THREE.Object3D();
var child= new THREE.Object3D();

var look_point = new THREE.Vector3();

grandParent.position.set(9,5,3);
grandParent.rotation.set(1,2,3);

parent.position.set(5,8,3);
parent.rotation.set(2,1,3);

child.position.set(2,5,3);
child.rotation.set(3,2,1);

scene.add(grandParent);
grandParent.add(parent);
parent.add(child);



var m = new THREE.LineBasicMaterial({ color: 0xFF00FF, blending: THREE.AdditiveBlending,  transparent: true, opacity: 1, depthTest: false })

/// draw line in scene
var v = new THREE.Vector3().copy(child.position);
    v = parent.localToWorld(v);
    v = grandParent.localToWorld(v);

var g = new THREE.Geometry();

    g.vertices.push(new THREE.Vector3().copy(v)); 
    g.vertices.push(new THREE.Vector3().copy(look_point));   


scene.add(new THREE.Line(g,m));    

// how to get relative points to draw line with child object as a parent

var g2 = new THREE.Geometry();

    g2.vertices.push(???); //// how to get Vector3 relative to child pos and rot?
    g2.vertices.push(new THREE.Vector3());   

child.add(new THREE.Line(g2,m));  

1 个答案:

答案 0 :(得分:2)

如果look_point在世界框架中,则需要将这些点转换为孩子的局部坐标框架。

您可以使用Object3D.worldToLocal函数来实现此目的。这是一个大概的想法:

// ensure the world matrices are all up to date
scene.updateMatrixWorld(true);

g2.vertices.push(child.worldToLocal(new THREE.Vector3().copy(v)));
g2.vertices.push(child.worldToLocal(new THREE.Vector3().copy(look_point)));   
child.add(new THREE.Line(g2,m));

重要的是要确保提前计算所有世界矩阵。让我知道这是否对您有用!