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);
}
}