# random direction of enemy when collide whit wall

hello,
I’m trying to move the enemies move randomly until they touch the wall and then again with random directions.

this is the script that i used for the random direction

``````public float speed = 5.0f;
public Vector3 direction;

void Start()
{
direction = (new Vector3(Random.Range(-1.0f,1.0f), Random.Range(-1.0f,1.0f),0.0f)).normalized;
transform.Rotate(direction);
}

void Update()
{
transform.position += direction * speed * Time.deltaTime;
}

void OnCollisionEnter (Collision col)
{
if (col.gameObject.tag == "Muri")
{
random ();
}
}

void random ()
{
Vector3	direction = (new Vector3(Random.Range(-1.0f,1.0f), Random.Range(-1.0f,1.0f),0.0f)).normalized;
transform.Rotate(direction);
}
``````

should be doing movements similar to the wandered of geometry wars and sometimes it works but many times when it touches the wall continues to move in that direction and I can not understand why, I made you a picture to make you understand what succedde sometimes when touching the wall.
[26886-enemy+movement.png|26886]

this is as it should be, and in fact every now and then it works but not always.

[26887-how+should+be.png|26887]

You can get the normal of the surface and then do a random angle axis rotation to get the new direction.

``````using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
public float speed = 5.0f;
public Vector3 direction;

void Start()
{
direction = (new Vector3(Random.Range(-1.0f,1.0f), Random.Range(-1.0f,1.0f),0.0f)).normalized;
transform.Rotate(direction);
}

void Update()
{
Vector3 newPos = transform.position + direction * speed * Time.deltaTime;
rigidbody.MovePosition (newPos);
}

void OnCollisionEnter (Collision col)
{
Debug.Log ("Collision");
if (col.gameObject.tag == "Muri")
{
direction = col.contacts[0].normal;
direction = Quaternion.AngleAxis(Random.Range(-70.0f, 70.0f), Vector3.forward) * direction;
transform.rotation = Quaternion.LookRotation(direction);
}
}
}
``````