Hi
I’m working on an AI demo showing steering behaviours and I’ve managed to get the behaviours working. The only issue I’m having is with collision and wall avoidance. I’m trying to use ray casting to detect if there is an obstacle in front of the ai (chicken) and if there is, move away from it but to no avail.
Here’s the ray casting code:
void avoidObstacles(GameObject gob)
{
Vector3 ahead = gob.transform.TransformDirection (Vector3.forward);
RaycastHit hit;
ahead = ahead.normalized;
if(Physics.Raycast(gob.transform.position, ahead, out hit))
{
Debug.DrawRay(gob.transform.position, ahead, Color.red);
Evade(gob, hit.transform.gameObject);
}
}
which I’m running in the update function:
void Update ()
{
//for every chicken follower, change their behaviour
foreach(GameObject gob in chickens)
{
avoidObstacles(gob);
}
…
and here is the Evade function code I’m using to move away from the obstacle ahead:
void Evade(GameObject obj, GameObject obstacle)
{
//find direction of target
Vector3 direction = obj.transform.position - obstacle.transform.position;
direction.y = 0.0f;
//calculate distance
float distance = direction.magnitude;
//if the target comes within proximity
if(distance < 2.0f)
{
//rotate away from it
obj.transform.rotation = Quaternion.Slerp(obj.transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
//move away from it
moveVector = direction.normalized * moveSpeed * Time.deltaTime;
obj.transform.position += moveVector;
}
}
so yea, unfortunately this isn’t working and my chickens disregard there being any obstacles and walk straight into them. Any help in figuring out this problem would be much appreciated.
Thanks in advance!