Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

three.js - how to translate geometry

I have a script that positions cubes of various width, height and depth and am struggling to line them up accurately based on the xAxis, yAxis and zAxis (which also vary).

var geometry = new THREE.BoxGeometry(width, height, depth);
var cube = new THREE.Mesh(geometry, material);
cube.position.set(xAxis, yAxis, -zAxis);
scene.add(cube);

I believe this is because the cube is positioned based on it's centre, however is there a method to position it based on the front, left and corner - which would solve this issue for varying sized cubes?

like image 771
wrdevelop Avatar asked Nov 02 '25 10:11

wrdevelop


1 Answers

You can translate your geometry so one corner of the box is located at the origin:

var geometry = new THREE.BoxGeometry( width, height, depth );
geometry.translate( width / 2, height / 2, depth / 2 );

If you have many cube instances of different sizes, it is better to use this pattern:

var geometry = new THREE.BoxGeometry( 1, 1, 1 ); // create once and reuse
geometry.translate( 0.5, 0.5, 0.5 );

var cube_1 = new THREE.Mesh( geometry, material );
cube_1.scale.set( width, height, depth );

three.js r.87

like image 155
WestLangley Avatar answered Nov 04 '25 00:11

WestLangley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!