我正在玩Three.js并制作太阳系的(简单!)模型。我正在尝试构建一个构造函数来构建行星和卫星,这是我到目前为止所尝试的但是我得到一个错误说:
setShadow()不是函数:
var body = function(size, color) {
this.sphere = new THREE.Mesh(new THREE.SphereGeometry(size, 32, 32),
new THREE.MeshLambertMaterial({color:color}))
return this.sphere
}
body.prototype = Object.create(THREE.Mesh.prototype);
body.prototype.constructor = body;
body.prototype.setShadow = function() {
this.sphere.castShadow = true
this.sphere.receiveShadow = true
}
或者,我尝试使用THREE.MESH.call(this, geometry, material)
,其中THREE.SphereGeometry = geometry
和THREE.MeshLambertMaterial = material
在构造函数之外定义。特别是这件事我需要担心Three.js还是我只是错误地接近这个?
编辑:替代尝试 - >
var body = function() {
THREE.Mesh.call(this)
return this
}
body.prototype.setShadow = function() {
this.castShadow = true
this.receiveShadow = true
return this
}
body.prototype = Object.create(THREE.Mesh.prototype);
body.prototype.constructor = body;
var example = new body(new THREE.SphereGeometry(70, 32, 32), new THREE.MeshLambertMaterial({color:this.getRandColor()}))
似乎所有内容都正确继承,但我对为什么setShadow函数无法正常工作感到困惑?
编辑2:尝试.call(this)
时实际上遇到了这个错误:
this.updateMorphTargets不是函数
答案 0 :(得分:1)
在扩展THREE.Mesh
类时,你在构造函数中犯了一个错误。
试试这样:
var Body = function(size, color) {
THREE.Mesh.call(
this,
new THREE.SphereGeometry(size, 32, 32),
new THREE.MeshLambertMaterial({color:color})
);
}
Body.prototype = Object.create(THREE.Mesh.prototype);
Body.prototype.constructor = Body;
无需在构造函数中返回任何内容,因为创建的对象将自动返回。
在您的setShadow
方法中,您应该只指向this
,因为属性castShadow
和receiveShadow
是新创建的Body
类的直接属性(继承自THREE.Object3D
到THREE.Mesh
)。
Body.prototype.setShadow = function() {
this.castShadow = true;
this.receiveShadow = true;
}
使用大写字母作为构造函数的第一个字符也是一种好习惯,因此在我的代码中,我将body
更改为Body
。确保相应地重命名所有其他引用。