Moving a Mesh with mouse/pointer without penetrate another mesh

Hi!

I have a question about collision between two meshes.

In the Playground below, I created two boxes. The box1 has a Behavior of being able to be moved with the mouse/pointer in z-axis and the box2 is fixed.

What I want to do is that box1 stop moving if it collides with box2, not being able to penetrate box2 or passing thorugh the other side.

The Playground: https://playground.babylonjs.com/#3F9X7S#1

What is the best / easiest way to do this?

I tried puttin a if for checking the position of box1 and returning it at a point before the box2, but when de user drags the box1, it still can penetrate box2.

Thank you!

At first glance, this would be a simple solution:
Test Colllision boxes - simple collision | Babylon.js Playground (babylonjs.com)

However, in order to update the position of the box, I had to call releaseDrag. This means that it will stop dragging as soon as there is a collision. It also means that you have to make sure to drag it away from the other box, when you begin dragging it.

I’ll see if I can give you a better solution in a few minutes, as I got some other ideas.

Edit:

I came up with a solution that uses 2 boxes for box1. One representing its collision shape and another representing it’s visual. That way you can decide when you want to update the position of the box.

Test Colllision boxes - snap collision | Babylon.js Playground (babylonjs.com)

2 Likes

Thank you @RandomlyFish !
Your second solution is exactly what I was looking for!

:clap:

You’re very welcome! :smile:

1 Like