I’m working on a game where the AI uses a raycast to find their target. However for some reason when the Human AI uses their raycast it goes off in a random direction. It doesn’t even try to hit the enemy. The Alien’s raycast works perfectly though.
If anyone could shred some light on why this is occurring I’d be very grateful.
Raycast wants a direction or point A to point B
When you take the enemy transform.posion and subtract your position, you are getting the difference between them.
so I would remove the subtraction part and give it a try.
if (Physics.Raycast (transform.position, go.transform.position, out hit)
Vector3 direction = (go.transform.position - transform.position).normalized;
Ray ray = new Ray(transform.position, direction);
RaycastHit hit;
bool hitSomething = Physics.Raycast(ray, out hit); // distance defaults to infinity
if(hitSomething) {
// do stuff
}
// DrawRay will draw from origin to (origin + direction), so you need to multiply in the distance.
Debug.DrawRay(ray.origin, ray.direction * Mathf.Infinity, hitSomething ? Color.green : Color.red);
Additionally, it seems that your logic is doing multiple identical raycasts per foreach iteration, which seems unnecessary. You should only need one raycast per loop, and then check the results for all your secondary conditionals.
Wow thanks for that knowledge! I really appreciate you taking time to expand on this for me. Raycasts and linecasts aren’t my strong point by any means, as you can probably tell. But this nice break down helps a lot!