- Home /
Enemy moving in a random direction
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?
Answer by Tehnique · Jul 15, 2014 at 08:08 AM
Your problem is at line 15:
direction *= -1;
That jsut switches the direction to backwards. Run the code inside your Start method again when you hit something so you pick a new random direction.
Also, use Update, not FixedUpdate.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Bat sine movement 2d Game help 3 Answers
Unity2d Top Down: Can't move character with Animator enabled 0 Answers