我有一个从THREE.Group类扩展的以下自定义类的实例:
class Screw extends THREE.Group {
//
constructor(){
super();
this.userData.length = 0; //length of screw starting at origin
}
add(desc){
var elem,
params = desc.split(" ");
if (params[0] == "GFA") {
elem = new GFAElement(params[1]);
} else
if (params[0] == "KB") {
elem = new KBElement(params[1]);
}
var elemLength = this.userData.length;
elem.position.z = elemLength;
this.userData.length += elemLength;
super.add(elem);
}
clone(){
//var m = new this.constructor().copy( this );
var m = super.clone();
m.position.y += -Cl;
m.rotation.z += Math.PI/2;
return m
}
}
其中组由以下类的元素实例组成:
class GFAElement extends THREE.Mesh {
constructor(params){
//
var p = params.split("-");
var userData = {
type: "GFA",
flights: parseInt(p[0]),
pitch: parseInt(p[1]),
length: parseInt(p[2]),
}
var shape = getProfile();
var extrudeSettings = {
steps: 5*userData.length,
depth: userData.length,
bevelEnabled: false
};
var geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings );
var material = new THREE.MeshStandardMaterial( {
color: 0xffffff,
metalness: 0.5,
roughness: 0.5,
} );
super( geometry, material );
this.geometry.vertices.forEach( vertex => {
var angle = 2*Math.PI/userData.flights*vertex.z/userData.pitch;
var updateX = vertex.x * Math.cos(angle) - vertex.y * Math.sin(angle);
var updateY = vertex.y * Math.cos(angle) + vertex.x * Math.sin(angle);
vertex.x = updateX;
vertex.y = updateY;
});
this.geometry.computeFaceNormals();
this.geometry.computeVertexNormals();
this.type = 'GFAElement';
this.userData = userData;
}
}
成功实例化螺丝对象并添加GFAElement后:
screw = new Screw();
screw.add('GFA 2-40-90');
screw.add('KB 5-2-30-90');
我要克隆此螺钉,将其旋转90度并平移一定距离。为此,我在Screw对象上有方法clone()
:
clone(){
//var m = new this.constructor().copy( this );
var m = super.clone();
m.position.y += -Cl;
m.rotation.z += Math.PI/2;
return m
}
但这会导致错误:Uncaught TypeError: params.split is not a function
可能是因为它试图重新实例化screw的子级,但是没有通过params
参数。使用m = super.clone(false)
“有效”但不会克隆子项。
如何克隆像上面这样的自定义类对象?
提琴here
编辑:
似乎在克隆子级(即GFAElements)时,以下对象作为参数params
(而不是默认字符串,即'GFA 2-40-90')传递给构造函数:
rb {uuid: "87141F9D-37D7-4295-9771-8E6CB1AC4F35", name: "", type: "ExtrudeGeometry", vertices: Array(86592), colors: Array(0), …}
由于该对象没有函数split()
而导致错误。