- Home /
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.
this is as it should be, and in fact every now and then it works but not always.
Thanks in advance!
Answer by robertbu · May 25, 2014 at 02:58 PM
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);
}
}
}
I edited the code. This code is tested and works for my simple example. The issue with my original code was I did not set 'direction'. I made a few other changes as well.
I don't know why but sometimes the enemy through the wall and inevitably move away from the scene. Through it, ignoring the collider. does not happen often but once in a hundred it and do not understand why.
I'm noticing that every time it happens there is a drop in frame rate, so it is not that at the time of the fall of the collision frame and fails to calculate and passes through?
Your answer
Follow this Question
Related Questions
Unity2D, How do i check which way a sprite is facing? 1 Answer
Enemy moves randomly within a area. 1 Answer
Need player to walk in random direction 2 Answers
2D Random AI 1 Answer
Enemy moving left towards player. 1 Answer