Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does world become undefined when passed as an argument to a constructor?

I’m trying to use threejs and cannonjs, but I’m getting this 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 relevant code is below:

objects.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 run after objects.js)

(both of them aren’t run as modules)

When I log world in script.js, it seems fine, but when I log it in Cube or BothObject, it’s undefined.

>Solution :

Your number of arguments doesn’t seem to match

(width, height, depth, mass, color,   scene, world) // Cube constructor
(100,   100,    0.1,         "green", scene, world) // new Cube

Use typescript to catch mistakes like this

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading