user134055
user134055

Reputation:

three.js: THREE.Vector3.sub() acting weirdly

Why does THREE.Vector3.sub return (0,0,0) in this scenario?

p0 = new THREE.Vector3( 0, 100, 50 );
p1 = new THREE.Vector3( 0, 50, 100 );
dummy = new THREE.Vector3(0,0,0);
p1_relative_to_p0 = dummy.sub(p1, p0);
console.log(p1_relative_to_p0);

this is the sub function from the THREE.Vector3's prototype:

sub: function ( a, b ) {
    this.x = a.x - b.x;
    this.y = a.y - b.y;
    this.z = a.z - b.z;
    return this;
},

console-output:

THREE.Vector3 x: 0 y: 0 z: 0

Why isn't the output (0, 50, -50) ?

The code can be seen in action here: https://dl.dropbox.com/u/2070405/webgl_lines_splines_jon.html

Upvotes: 1

Views: 2487

Answers (2)

Bubbles
Bubbles

Reputation: 3815

I attempted to duplicate the behavior here, but it worked exactly as you intended. Any chance you were just accidentally reading values from the wrong area?

Upvotes: 1

pimvdb
pimvdb

Reputation: 154918

You fell victim of the console.log caveat. In Chrome, a logged object is evaluated when you expand it, not when you log it.

Due to return this, it is true that p1_relative_to_p0 === dummy. You're updating dummy later on and thus also p1_relative_to_p0, because objects are shared in JavaScript. When you expand the object, you're effectively reading dummy's contents, which have been set to 0, 0, 0 in the meantime.

Try setting a breakpoint instead of the log to halt execution to observe the right values.

Upvotes: 2

Related Questions