Performance issue due to Raycast

Hey,

I have a problem. When adding following lines code to my scene the performance drops from way over 30 fps to 2 fps.

 var hit : RaycastHit;
if(Physics.SphereCast(transform.position,30,transform.forward,hit,10))
{

 	if(hit.transform != this.transform)
	{
     	if(hit.collider.tag == "Player" || hit.collider.tag == "AI" || hit.collider.tag == "Environtment")
     	{
     	       inputTorque = 0.0;
      		inputBrake = 1.0;
      		Debug.Log(gameObject.name + " Collides with "+ hit.collider.name);
    	}
   	}

}

The script is supposed to check if there is another Car in front of my car and in case there is the car is supposed to break. I thought that using a simple ray cast would be the easiest but I was quiet astonished by the huge performance problem coming from it. Because if I comment out those lines, the scene will work perfectly again.

So there is a maximum of 6 ai cars in the scene so I thought that 6 ray casts shouldn’t be too bad. Would be nice if anybody would have some suggestion what I made wrong or if somebody would have any suggestion on how I could check another way if there is a car in front.

Place a rigid body with a collider ahead of your car. It doesn’t have to have a mesh. If it collides with something, then take appropriate action. In that way, you can avoid ray casting at all, which is very computationally expensive, especially with spherecasts.

— First of all sorry that I still can’t find the comment function —

Why am I using a sphere cast? well I don’t want to check just one point but the whole area in front of my car.

Well I also thought about the collider thing but when the car has to turn this often results in problems. And I was going to replace the “10” in the sphere cast by a variable depending on the speed so that when the car drives faster it also ray casts a longer distance and when it turns I was also going to do some adjustment on the direction it casts.

A mere 6 spherecasts shouldn’t be slowing you down that much. CompareTag is faster than tag== (I think.) Could add a layerMask to only check vs. cars. But, for speed and game fun, you can just do it every 10 frames, with a counter:

// start this different 0-10 for each car,
// so they always alternate frames doing it:
public int framesUntilCast;

if(framesUntilCast>0) FramesUntilCast--;
else {
  FramesUntilCast=10;
  // do sphereCast here
}

Checking less often makes it look like the drivers have non-perfect reaction times.

Also, wondering about the radius of 30 meters on the sphereCast. Without a layerMask, that’s always going to hit the ground. Also the car 30 meters to your left.