How to have 2 objects share the same x (position) value, player can push any of them and another will move too?

In game, there are boxA and boxB. They are start on same x but may have different y and z.

If player push boxA to x = -10, boxB will move to x = -10 as well. In the same manner, If player push boxB to x = 20, boxA will move to x = 20 as well. (the boxes’ rigidbody have freezed y and z and freezed rotation.) (nothing other than player can cause the boxes to move and player can not actually push both boxes at the same time)


I have tried to script boxA to get Transform of boxB and update boxA.transform to have same x of boxB.transform but that locks boxA from being pushed by player (It wont move when player push).
Another idea I can think of is to get total force from boxA and copy it to boxB but I cannot find api to get totalforce from a rigidbody.

HI @abcteapatipol, just set:

   RigidbodyB.positon = RigidbodyB.positon + new Vector3( RigidbodyA.positon.x, 0, 0 );

If you are using the Physics Engine, do not set transform.position ! You must use the Rigidbody instead in order to not mess up the Physics Engin calculations.

Sorry, slight error above - that will add A’s x to B’s x, but what you want to add the difference between them.

So:

   float offset = RigidbodyA.positon.x - RigidbodyB.positon.x;
   RigidbodyB.positon = RigidbodyB.positon + new Vector3( offset, 0, 0 );