After a collision, stop moving

As shown in the title, let me give an example to explain in detail: when a group moves to the left on the x-axis and encounters other groups, if it continues to move to the left, it stops moving.

My question: If you approach slowly, there is no gap between the stops, if you move fast, there is a gap between the stops after impact.
My idea to remove the spacing is to judge its direction, then measure the position between the two meshes, if it’s the y-axis, then subtract half of the respective heights, if it’s the x-axis, subtract half of the respective widths, if it’s the z-axis , minus half of their respective depths. Then add the dwell position of the mesh before impact. It feels cumbersome, is there a better solution?