Hi!
I’m kinda new here and I’m currently working on a project that requires me to snap some meshes together when they are near each other. Let’s assume I have two tables: one is the classic rectangular table and the other is a curved table. Here is an image of what I’m trying to achieve.
I can move one mesh with the mouse and drag it around. When I snap two meshes (or more) together I want to move them all at the same time.
As you can see, there are some green sides and those are the sides allowed to snap with other meshes when they are near them. The snapped mesh must also be aligned with the side of the other mesh.
How can I achieve this in BabylonJs (considering I need it to be compatible with all kind of shapes of these meshes)?
As of now I’ve tried to use rays from the mesh I’m moving with the mouse to interesect other meshes but I have no idea how I can align the two tables like in the “After” part of the picture.
I understand I cannot rely on bounding boxes for alignment because of the curved table and the fact that I need to align my other mesh to its shorter side as in the picture above.
How would you go about this? Is there something I need to do to my meshes when I create them to allow this behavior?
I’d appreciate some advice on how to achieve and handle this. Thank you very much.
It sounds like you want to detect if two planes are parallel to each other, and allow the meshes to snap together if so. You can use some simple math to determine whether planes are parallel:
Parallel, perpendicular, and angle between planes — Krista King Math | Online math tutor
To get the meshes to “stick together”, I think you can roughly do the following:
- calculate the offset between each plane and the center of its mesh.
o1: (mesh1.plane.center - mesh1.position)
o2: (mesh2.plane.center - mesh2.position)
- Adjust the position of the mesh that’s doing the snapping:
mesh2.position = mesh1.position + o1 + o2 (maybe play with the signs here to get the intended effect)
If you want to detect if two meshes should start snapping, you can probably just compute the distance between mesh1.plane and mesh2.plane, and set snapping=true if it’s below some constant.
I haven’t tested this personally, but I don’t see why this wouldn’t work.
The only thing missing here is getting the list of all planes in the mesh I don’t know if Babylon provides an easy way to do this…this might be some extra metadata that you need to generate when creating your meshes, or else create by hand. The advantage of doing it by hand is that you can define exactly which planes should be snappable…they need not necessarily correspond to actual geometry of the mesh.
3 Likes
Sorry for being so late! Work crushed me this week…
You actually gave me the correct idea to handle this situation so thank you very much.
I ended up adding some specific planes to my meshes.
2 Likes