Comparing two vectors

Hello! I’m new to Three.js and would like to create a Dual N’Back style game in 3D. One aspect of the game is pressing a button when the object appears in the same location it did x number of rounds ago and I was just wondering how you could compare the value of two vectors(?) in Three.js. Here is some code I have written so far to state the location of the cube8 object (it’s pretty basic):

``````		function AnotherFunction() {

gsap.to(cube8.position,3, { y: Math.floor(Math.random()*5)});
gsap.to(cube8.position,3, { z: Math.floor(Math.random()*5)});
gsap.to(cube7.position,3, { x: Math.floor(Math.random()*5)});
gsap.to(cube7.position,3, { y: Math.floor(Math.random()*5)});
gsap.to(cube7.position,3, { z: Math.floor(Math.random()*5)});
gsap.to(cube6.position,3, { x: Math.floor(Math.random()*5)});
gsap.to(cube6.position,3, { y: Math.floor(Math.random()*5)});
gsap.to(cube6.position,3, { z: Math.floor(Math.random()*5)});
gsap.to(cube6.position,3, { z: Math.floor(Math.random()*5)});

let Vectorforcube = THREE.Vector3();
const printlocation = cube8.getWorldPosition(Vectorforcube);
console.log(printlocation);

const r3 = (Math.random()*150);
const g3 = (Math.floor(Math.random()*10));
const b3 = (Math.random());
materialf.color.setHSL(r3,g3,b3);
renderer.render(scene, camera);
}
``````

Well, you can use Vector3.equals() if you want to check for equality. However, if you need more flexibility because of floating point inaccuracies, you can monkey-path `Vector3` with your own equals method like so:

``````equals( v, epsilon = Number.EPSILON ) {

return ( ( Math.abs( v.x - this.x ) < epsilon ) && ( Math.abs( v.y - this.y ) < epsilon ) && ( Math.abs( v.z - this.z ) < epsilon ) );

}
``````
4 Likes

Thanks @Mugen87 - that’s great! I’ll have to try it out this evening.

`equals()` probably would more often fail than work? Very hard to do math operations and get all three numbers to be exactly the same? It’s a good idea to check most floats with an epsilon, not just the vector.