tforgione
tforgione

Reputation: 1235

Can't copy a THREE.Vector3

I think my problem is more a javascript inheritance problem than a Three.js one.

I am not very familiar with inheritance in javascript, so after a few tutorial, I came up with this snippet and I can't figure out why it doesn't do what I expect.

var MyClass = function() {

    THREE.PerspectiveCamera.apply(this, arguments);   

    // Here this.position is default value, (0,0,0)

    this.position = new THREE.Vector3(1,2,3);

    // this.position is unchanged, like if 
    // the previous affectation didn't do anything

}

MyClass.prototype = Object.create(THREE.PerspectiveCamera.prototype);
MyClass.prototype.constructor = MyClass;

var obj = new MyClass();

This does what I expect it to do if I remove the inheritance, and I can't reproduce this with stuff other than Three.js objects.

There is probably something I'm missing, but I can't see what.

Do you have an idea ?

Thank you !

Upvotes: 2

Views: 1195

Answers (2)

WestLangley
WestLangley

Reputation: 104833

You cannot assign an object's position a new THREE.Vector3, as you are doing:

this.position = new THREE.Vector3( 1, 2, 3 );

As explained in this answer, Object3D's position, rotation, quaternion and scale properties are immutable. Use the set() method, instead.

this.position.set( 1, 2, 3 );

three.js r.71

Upvotes: 3

DavidVollmers
DavidVollmers

Reputation: 695

The way inheritance is supported in javascript is really complex and if you don't want to write code you and your mates can't read after a few months then you should think about another way to solve your problem.

I think of a wrapper constructor around THREE.PerspectiveCamera.prototype:

var MyClass = function () {
    this.perspectiveCamera = new THREE.PerspectiveCamera(arguments);
    this.perspectiveCamera.position = new THREE.Vector3(1, 2, 3);
}

var instance = new MyClass();

This should do the trick.

But if you are interested in the prototype concept, here are a few good to knows:

  • passing an instance of a structure to a prototype means, that all instances of this prototype will reference to the same instance of the structure

  • you should never set an prototype to an instance of another prototype, because this will eventually include some structures (see above)

  • the best way is to iterate through all members of the old prototype (recursivly) and clone them to the new prototype.

some links for further knowledge:

https://developer.mozilla.org/de/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

http://snook.ca/archives/javascript/javascript_pass

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

Upvotes: 4

Related Questions