Restricting Position Between Two Points

Hi, I am making a game in which the red cube has to move between two borders (blue ones). I have a script to move it, but it should not go through borders. Check the screenshot.

Thanks you in advance

There are a couple ways to restrict the cube.

  1. If the blue items are static you can use Mathf.Clamp(…) function on the x-axis value of the cube. I.e. The red cube x-axis value is clamp between a low value (right cube inner edge) and high value (left cube inner edge).


  1. You can use physics and colliders (a box collider on the two borders scaled to their size) and a box collider and dynamic (Kinematic tick off) rigidBody component added to the cube. You’ll need to switch off gravity on the red cube rigidBody as well.

Moving objects around in physics is different to just adding values to the transform x,y,z values of the cube. You’ll need to apply forces and think about both angular and direction velocity drag (to slow the cube over time). You can lock things like angular velocity if you don’t want the cube to spin.

Have a look at Physics Challenges - Unity Learn - It’s a good primer for the simpler side of physics in Unity.