- Home /
Problem with AI dodging obstacles
Hey guys, I was following a tutorial on AI avoiding obstacles. The tutorial was in JS and i tried to convert it to C# along with some of my own code, Now the movement works fine and it casts the rays fine, but it doesnt avoid any of the obstacles. It simply runs through them and i cant figure out why, I have added a rigid body to the obstacle. Here is the code, Thanks in advance!
public class enemyAI : MonoBehaviour
{
public Transform target;
public float moveSpeed;
public float rotationSpeed;
public int maxDistance = 2;
public static enemyAI enemyAIself;
RaycastHit hit;
//private Transform myTransform;
// Use this for initialization
void Awake()
{
enemyAIself = this;
//myTransform = transform;
}
void Start ()
{
GameObject goTo = GameObject.FindGameObjectWithTag("Player");
target = goTo.transform;
}
// Update is called once per frame
void Update ()
{
Vector3 dir = (target.position - transform.position).normalized;
if (Physics.Raycast(transform.position, transform.forward, out hit, 5))
{
if(hit.transform != transform)
{
Debug.DrawLine(transform.position, hit.point, Color.blue);
dir += hit.normal * 50;
}
}
Vector3 leftR = transform.position;
Vector3 rightR = transform.position;
leftR.x -= 2;
rightR.x += 2;
if (Physics.Raycast(leftR, transform.forward, out hit, 5))
{
if(hit.transform != transform)
{
Debug.DrawLine(leftR, hit.point, Color.blue);
dir += hit.normal * 50;
}
}
if (Physics.Raycast(rightR, transform.forward, out hit, 5))
{
if(hit.transform != transform)
{
Debug.DrawLine(rightR, hit.point, Color.blue);
dir += hit.normal * 50;
}
}
Debug.DrawLine(target.position, transform.position, Color.red);
//look at our target
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position - transform.position), rotationSpeed * Time.deltaTime);
if (Vector3.Distance(target.position, transform.position)> maxDistance)
{
//move towards the target
transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
}
}
Answer by getyour411 · Sep 20, 2013 at 09:31 PM
Don't do this
transform.position += transform.forward * moveSpeed * Time.deltaTime;
Moving via transform ignores stuff, it's like a mini teleport. Look at something like SimpleMove
http://docs.unity3d.com/Documentation/ScriptReference/CharacterController.SimpleMove.html
Hey thanks for the reply, I dont know if I want to add a character controller to all the enemies that spawn though
Then you'll have to apply forces of your own to move them properly; Google Unity Physics force/velocity, etc.
Your answer
Follow this Question
Related Questions
Obstacle Avoidance 0 Answers
Follow AI which avoides obstacles 1 Answer
obstacles avoidance in C# 1 Answer
How to make my enemy jump over obstacles? 2 Answers
How can I make an AI that avoids obstacles WITHOUT using NavMesh? 3 Answers