Why to set maximum and minimum for transform.position of an object?

I have an object (with rigidbody2D) that I move, with this code:

thePrefab.transform.position.x += 2 * Input.GetAxis("Horizontal"));

I have 2 box colliders on each side of the object, in order to limit how far right and left the object can go.
The problem is the colliders don’t stop the object completely.

  • When the translation is slow, the object slightly breaks through the collider
    and bounces off of it.

  • When the translation is fast, it completely ignores the collider and
    breaks through it

How can I make sure that the object does absolutely not go past that collider?
Is there more than one efficient way?

Instead of using colliders, why don’t you just clamp the movement.

Which axis is the side movement? Let’s imagine it’s X

transform.position.x = Mathf.Clamp (transform.position.x, -5, 5);

Where -5 and 5 are the minumum and maximum side movements, that you allow it to go.

So your character will never go side more than 5 units from the center of the path…