In my game, I have an enemy which should be moving randomly. First it’s chosing a random direction, than is starting moving to that direction. When it’ll hit a “wall” (maze) it should change the direction, again (randomly). Here is my code in which when hits a “wall” it returns to the same direction.
public Vector3 target;
public float speed=10f;
int direction = 1;
void Start (){
target = Random.insideUnitSphere * 5;
transform.Rotate(target);
}
void FixedUpdate() {
rigidbody2D.MovePosition(rigidbody2D.position + ((Vector2)(transform.forward * speed * Time.deltaTime * direction)));
}
void OnCollisionEnter2D (Collision2D coll){
Debug.Log ("hit.");
if (coll.gameObject.tag == "maze" || coll.gameObject.tag == "coin"){
if (screenPos.x < Screen.width / 2){
direction *= -1;
Debug.Log ("change_2.");
}
}
}
Can somebody help me fix this?