Moving cube only a certain distance.

I have a square terrain with cylinders placed at each corner, and cubes placed in the middle of each side. I only want the cubes to move in a side-to-side direction and stop when it touches a cylinder at each end. What happens instead is that the cube does indeed move only side to side, but it’ll continue to go in either direction and pass through the cylinders. How do I prevent this?

Here is a script of how I tried to handle this, but the behavior remains the same:

using UnityEngine;
using System.Collections;

public class PlayerBehavior : MonoBehaviour
{
    bool collideLeftBottomBarrier = false;
    bool collideRightBottomBarrier = false;

    void Start () { }

    void OnCollisionEnter(Collision collisionInfo)
    {
        if (collisionInfo.gameObject == GameObject.Find("LeftBottomCylinder"))
        {
            collideLeftBottomBarrier = true;
        }
        if (collisionInfo.gameObject == GameObject.Find("RightBottomCylinder"))
        {
            collideRightBottomBarrier = true;
        }
    }

    void OnCollisionExit(Collision collisionInfo)
    {
        collideLeftBottomBarrier = false;
        collideRightBottomBarrier = false;
    }

    void Update ()
    {
        float x = Input.GetAxis("Horizontal") * Time.deltaTime * 10;
        if (collideLeftBottomBarrier  Input.GetKey(KeyCode.LeftArrow) ||
            collideRightBottomBarrier  Input.GetKey(KeyCode.RightArrow)) {
            x = 0;
        }
        transform.Translate(x, 0, 0);
    }
}

What physics options do you have on both objects(the collider and collidee?)?

I believe they’re still the defaults, except I’ve set both materials to ‘Bouncy.’

I think that you need to add the Rigidbody component to the Cube game object.

MightyMao is correct, do that next and then let us know if you still have issue.

I did that but when colliding with other objects it would get knocked off track, so I changed the mass to 5000 and then redid the code like so:

using UnityEngine;
using System.Collections;

public class PlayerBehavior : MonoBehaviour
{
    void Update ()
    {
        float x = Input.GetAxis("Horizontal") * Time.deltaTime * 10;
        transform.Translate(x, 0, 0);

        if (rigidbody.position.x < 1.5f)
        {
            float y = transform.position.y;
            float z = transform.position.z;
            transform.position = new Vector3(1.5f, y, z);
        }
        else if (rigidbody.position.x > 8.5f)
        {
            float y = transform.position.y;
            float z = transform.position.z;
            transform.position = new Vector3(8.5f, y, z);
        }
    }
}

So now it works, though if there’s a better way to do this I’m all ears.