Raycast & AI problem.

I have this here AI and it is retarded. The problem is that I can’t get it to stop seeing the target it looks at when going out of view like going behind another gameobject with collider.

I had actually gotten it to work(in a very bad way) before but it was all in LateUpdate which was making it lag and just kind go crazy. It just looked wrong in the LateUpdate too.

So after I gave the raycasting its own void the thing stopped detecting the colliders. The other codes I have seen don’t use late update to do it so I know its something else.

So let me clarify. The rays and raycasting is working but its not detecting other colliders and or is ignoring them utterly. The AI does however detect the player with the tag and acts accordingly. It also does not detect the maximum distance of the rays which if the target exceeds then it is supposed to stop doing some things, which it does not.

Anyway here is the code or at least the part where the problem is coming from. Main part being the RayCasting().

    void Update (){
			
		AIRayCasting();
		
	if(canFollow == true){
			
		   Following();
		  
	if(stopFollow == true){	
		
		StopFollowing();
	
		}
		
		}
	}

	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);
			

         if(aimhit.transform.tag == "Player"){ 
					
		    canFollow = true;
		    looking = true;

			target = aimhit.transform;
					
					
				}else{
	    						
					StopFollowing();
						
					}
			
				}
	
			}
		}

Hope I was clear.

It is hard to tell what is going on with this thin slice of your code. ‘canFollow’ is never set to false here. We don’t see how ‘stopFollow’ get set, and it looks like you are calling StopFollowing() in one too many places. Plus you don’t bail out of your ‘for’ loop if the player is spotted, which means that StopFollowing() gets called every time the raycast fails even if some of the raycasts succeed. This is likely the cause of your problem. Try putting a ‘break’ statement on line 18.

Note rather than raycast a bunch of rays, why not just check the angle between your forward and the player? Something like:

Vector3 v3 = player.position - transform.position;
if (Vector3.Angle(v3,  headdummyBone.forward) < fovAngle / 2) {
   // Sees the player
}

This will behave differently than your current code since it will also spot the player if he is below or above your fan of rays.

And a RaycastHit is a struct, so you don’t have to do a ‘new’ to initialize it.