- Home /
Another Raycast Issue.
This is related to my previous question.
This time the problem is that the raycast is not working well, not that it isn't working. I tried many things but I just can't get it right.
The problem: Even though the rays are cast they don't cast out properly. It instead seems to use one ray as the main ray and almost pivots the rest of the rays on it. Its the first ray in number of rays. The rays cast a different number depending on the angle and when facing say south, only one ray or none are cast.
I don't know what the hek is going on.
Here is the code.
void AIRayCasting(){
numRays = fovAngle;
currentAngle = fovAngle / -2;
hits.Clear();
for (int i = 0; i < numRays; i++)
{
direction = Quaternion.AngleAxis(currentAngle, transform.up) * headdummyBone.forward;
RaycastHit aimhit = new RaycastHit();
if(Physics.Raycast(headdummyBone.position, direction, out aimhit, maxSeeDistance)){
hits.Add(aimhit);
currentAngle += 1f;
Debug.DrawRay(headdummyBone.position, direction * maxSeeDistance, Color.blue);
int hitsIn = 0;
foreach(RaycastHit rhit in hits){
if(rhit.transform && rhit.transform.tag == "Player"){
hitsIn++;
canFollow = true;
looking = true;
target = aimhit.transform;
break;
}else{
StopFollowing();
}
}
}
}
} //You were missing a "}" maybe a copy error?
//Peter G
Oh yeah that is a copy error.
To rephrase, the code has no errors and is partially working. The main problem is that the rays don't cast properly which is dependent on the angle the AI(which the code is on) is facing.
The hek is going on lol?
Let me explain a little better.
When the this AI dude is facing say north all the rays that are meant to be cast are cast and it detects anything that is hit by them, however if I start turning player through code or manually the number of rays start decreasing until all gone as it turns. It only happens towards certain angles/directions.
I don't see a problem that would cause the specific issue you describe, but I do see a couple of things. First in your Quaternion.AngleAxis(), your use of 'transform.u'p could cause problems depending on the relationship of the 'headdummyDone' to this game object. First choice would be 'headdummyBone.up' or maybe 'Vector3.up'.
The second problem is your inner 'foreach(RaycastHit rhit in hits)' loop. You are rechecking the same rays over and over again. If you need to save the RaycastHits for some other use, then this code should be moved outside the 'for (int i = 0; i < numRays; i++)' loop. Or if you don't need to save the hits, then remove it and check the curent hit.
When I remove the foreach then the raycast doesn't let the target pass through the rays it ins$$anonymous$$d pivots the whole set of rays on the one ray on the target, which makes the thing effectively only have one ray on the target, which then makes it lose sight very very quick.
However I think I will remove the foreach, as it hits the FPS pretty hard I just found out.