I'm attempting to utilize threejs and cannonjs in my project, but I'm encountering the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'copy') at World.add.World.addBody (cannon.js:12985:23) at new BothObject (objects.js:15:16) at new Cube (objects.js:33:5) at script.js:7:15
The code snippet causing the issue is shown below:
objects.js
class BothObject{
constructor(shape,geometry,mass,color,scene,world){
this.scene=scene
this.world=world
this.physics = new CANNON.Body({
mass: mass, // kg
});
this.physics.shape=shape
this.geometry = geometry;
this.material = new THREE.MeshPhongMaterial( { color: color});
this.mesh = new THREE.Mesh(this.geometry,this.material)
console.log(world)
this.scene.add(this.mesh)
this.world.addBody(this.physics)
}
update(){
this.mesh.position.copy(this.physics.position)
this.mesh.quaternion.copy(this.physics.quaternion)
}
}
class Sphere extends BothObject{
constructor(radius,mass,color,scene,world){
super(new CANNON.Sphere(radius/2),new THREE.SphereGeometry(radius),mass,color,scene,world)
}
}
class Cube extends BothObject{
constructor(width,height,depth,mass,color,scene,world){
super(new CANNON.Box(new CANNON.Vec3(width/2,height/2,depth/2)),new THREE.BoxGeometry(width,height,depth),mass,color,scene,world)
}
}
script.js:
console.log("start")
const scene = new THREE.Scene();
scene.background = new THREE.Color( 'skyblue' );
var world = new CANNON.World();
world.gravity.set(0,0,-9.82);
var gground = new Cube(100,100,0.1,"green",scene,world)//it's gground because I have another variable named ground
(script.js is executed after objects.js)
(neither are run as modules)
When I log world in script.js, it appears to be functioning properly. However, when I log it in Cube or BothObject, it returns as undefined.