SetFromObject (mesh) returns incorrect values, sometimes

THREE.Box3.setFromObject(*object*) returns invalid values. The best way to show you, showing you how I deal with it:

I create 2 cells from the vertices. The first with the triangle() function, the other with trapezoidForm() .

 var triangle = function (base, height) { return [ new THREE.Vector2(0, -height / 2), new THREE.Vector2(-base / 2, height / 2), new THREE.Vector2(base / 2, height / 2) ]; } var trapezoidForm = function (base, upperBase, height) { return [ new THREE.Vector2(-base / 2, height / 2), new THREE.Vector2(-upperBase / 2, -height / 2), new THREE.Vector2(upperBase / 2, -height / 2), new THREE.Vector2(base / 2, height / 2), ]; } 

I use the return value to create my grid:

 var material = new THREE.MeshPhongMaterial({ color: 0x666666, /*specular: 0x101010*//*, shininess: 200*/ }); var shape = new THREE.Shape(vertices); var mesh = new THREE.Mesh(new THREE.ShapeGeometry(shape), material); 

And use this to place it in the scene, and create a bounding box:

 mesh.position.set(posX, 0, posZ); mesh.rotation.set(-Math.PI / 2, 0, 0); boundingBox.setFromObject(mesh); 

Now I want to find the center of my two forms. Easy enough: I take a bounding box and figure it out. Like this:

 var centerX = (boundingBox.max.x + boundingBox.min.x) * 0.5; var centerZ = (boundingBox.max.z + boundingBox.min.z) * 0.5; 

Here's where it goes wrong: for a triangle, it calculates the right place, but for a trapezoid it's a mess.

Below is the print screen on the console. The first three vertices for the triangle, followed by the bounding box. The next 4 are for the trapezoid, with the bounding box again. For vertices: the first number is the X-coordinate, the second is the Z-coordinate.

Console log showing a problem

Desired result: the second bounding box should return something like:

 max: X: 200 Z: 200 min: X: -200 Z: -100 

Image showing the current state (the triangle has a minus sign in the middle, there is no trapezoid):

situation state

+5
source share
1 answer

I found the solution myself at the end:

I need to create my bounding box before moving it or rotating it:

 //Boundingbox boundingBox.setFromObject(mesh); mesh.position.set(posX, 0, posZ); mesh.rotation.set(-Math.PI / 2, 0, 0); 

instead:

 mesh.position.set(posX, 0, posZ); mesh.rotation.set(-Math.PI / 2, 0, 0); //Boundingbox boundingBox.setFromObject(mesh); 

the reason the triangle didn't cause problems was because it was mapped to 0.0.

0
source

Source: https://habr.com/ru/post/1236967/


All Articles