Detect picked face of mesh

I am making a little voxel clone before the main work on NYNS. I started in the playground, but I’m moving it to the editor later. Right now the system in which I detect what side of a cube to place a block on is kinda primitive. It doesn’t work 100% of the time, but it doesn’t misplace a block.

Playground here: https://playground.babylonjs.com/#D1Z1VL#1

At lines 67 - 91 is where it takes place. The variables xx, xxx, yy, yyy, zz, zzz are what control where to place the blocks. lines 85, 86, and 87 are the side detection. They compare the distance from the picked mesh (for the original cube 0,0,0) with the picked point. It looks for which variable (in this case xx, yy, and zz) is equal to 0.5. Since the cube is 1 x 1 x 1, the distance from the center to a side should be 0.5. Sometimes it is 0.49999999999999999 and can be seen if you add a console.log.

I’m wondering if there is any better way to the the side detection.

Thanks for any help,
Givo.

BABYLON.PickingInfo has a faceId property. I would venture a guess that for boxes, there are likely 12 faces (2 triangle faces per side). Figure out which faceId is equal to the direction you want to add a box in and you should be golden. Better than doing floating point math and should work always, even if you are hitting an edge point.

Thanks! I saw the FaceId thing and didn’t know how it could be used. I’ll read up on it and try it out!

I just found these lines of code in a playground:

var face = pickResult.faceId / 2
var facet = 2 * Math.floor(face);

facet is turned into a number between 0-10
0 is positive Z
2 is negative Z
4 is positive X
6 is negative X
8 is positive Y
10 is negative Y

I’ll just make a few if-else statements and it’ll work!

2 Likes

New issue!

https://playground.babylonjs.com/#D1Z1VL#2

I made the crosshair equal the number of blocks in the scene. (controlled by the variable cubes)
It goes up, but the last block disappears when you place a new one. What’s happening? :confused:

All the the boxes are sharing the same position. When doing .position = .position that is a reference.
you need to clone the position .position = .position.clone() or copy it .position.copyFrom(.position)

https://playground.babylonjs.com/#D1Z1VL#3

Thanks! It’s great!