- Home /
AI Pathfinding using RayCast
I am trying out a raycast script for pathfinding, not to go to any specific location but just to get my npc to walk around the map Whilst adjusting its direction to avoid collision. I'm not sure if I am taking the right approach here so any advice or insight would be great. my full script is :
public float speed = 25f; public float distance = 100f; public GameObject origin;
void Update()
{
RaycastHit hitInfo;
if (Physics.Raycast(origin.transform.position, -origin.transform.forward, out hitInfo, distance))
{
if (hitInfo.transform != null)
{
Debug.Log("Changing Direction");
changeDirection();
}
else
{
Debug.Log("Moving Forward");
MoveForward();
}
}
}
void changeDirection()
{
RaycastHit hitInfo;
RaycastHit hit;
float straffeSpeed = 15f;
float turnSpeed = 10f;
if (Physics.Raycast(origin.transform.position, -origin.transform.forward, out hitInfo, distance))
{
if (Physics.Raycast(origin.transform.position, -origin.transform.right, out hit, distance))
{
if (hit.transform != null && hitInfo.transform != null)
{
Debug.Log("Turning Right");
transform.Translate(Vector3.right * straffeSpeed * Time.deltaTime);
transform.Rotate(Vector3.up * -turnSpeed * Time.deltaTime);
if (Physics.Raycast(origin.transform.position, -origin.transform.forward, out hitInfo, distance))
{
if (hitInfo.transform == null)
{
MoveForward();
Debug.Log("Turning Right Finshed, Moving Forward Now");
}
}
}
if (hit.transform == null && hitInfo.transform != null)
{
Debug.Log("Turning Left");
transform.Translate(Vector3.right * straffeSpeed * Time.deltaTime);
transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
if (Physics.Raycast(origin.transform.position, -origin.transform.forward, out hitInfo, distance))
{
if (hitInfo.transform == null) {
MoveForward();
Debug.Log("Turning Left Finshed, Moving Forward Now");
}
}
}
}
}
Update();
}
void MoveForward()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
Update();
}
what I want it to happen is to cast a ray forward and if there is an object in front then cast a ray to the side and decide from there which direction is clear to go. But on startup nothing happens. So any help or advice just anything will be muchly appreciated
Your answer
Follow this Question
Related Questions
For each Raycast? 1 Answer
AI Field of vision 1 Answer
Another Raycast Issue. 0 Answers
C# mouse Raycast question 3 Answers
Setting a point with a ray C# 1 Answer