Check for collision with wall and move in a new direction

I made a post similar to this but it seems to be dead and being as I have new version of code I thought it would be best to explain in more detail.

The problem is that my code doesnt seem to work - the cube moves through the wall somtimes and other times freezes after hitting a wall.

Goal:
To automate the movement of a cube within a enclosed area with four walls. If it collides with a wall the cube should move in a new random direction. It can only move forward/backward , and digonally.

My approach:

Check for collisions:

``````function OnTriggerEnter (hit: Collider)

{
if(hit.gameObject.tag == "wall")

{
//rotate in new direction
transform.rotation = Quaternion.AngleAxis(180, Vector3.up);
FishAI.directionAvailable = false;
}
else
{
FishAI.directionAvailable = true;

}

}
``````

Then generate a random direction and move in that direction:

``````static var directionAvailable = false;
static var randomNumber: int;

function Awake()
{
//print ("no collision as of yet");

}

function Update () {

if (directionAvailable == false)
{
//randomNumber = (Random.Range(1, 4));
randomNumber = (randomNumber + Random.Range(1, 3)) % 3;
print (randomNumber);
directionAvailable = true;

}

//Use values obtained from above to move Fish
//forward
if (randomNumber == 1)
{
transform.position.x += 0.04;

}

// left diagonal
if (randomNumber == 2)
{
transform.position.z += 0.04;
transform.position.x += 0.04;
}

// Right Diagonal

if (randomNumber == 3)
{
transform.position.z += 0.04;
transform.position.x -= 0.04;
}

}
``````

It might be worth me starting from scratch?

Generally, triggers work much better as stationery objects than they do when they move. You will probably get better results by using a normal collider with your object and using OnCollisionEnter to tell you when it runs into a wall. Also, make sure the moving objects each have a rigidbody component with the Is Kinematic property switched on.