Raycast without using a collider

freeDom- picture freeDom- · Feb 24, 2015 · Viewed 7.7k times · Source

I am doing a Voxel game and my engine was using Physics.raycasts and Mesh colliders for getting the coordinates of the block you clicked on until now. I decided to remove the mesh collider, because it was just eating too much performance in some situations and I got fps dropdowns to 0.1fps for a few seconds (eg you should be able to scroll through the y-layers) and I only needed it for raycasting. I don't use any other physics related stuff. Without the mesh colliders the framerate is stable at 60 to 100 fps, but now I find it hard finding another way getting the information on which block I am clicking.

Any suggestions?

So far I was using this piece of code:

public Vector3? GetBlockCursor(){
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit)) {
        hit.point += (hit.normal * -0.5f);
        hit.point = new Vector3(Mathf.RoundToInt(hit.point.x), Mathf.RoundToInt(hit.point.y),
                                Mathf.RoundToInt(hit.point.z));
        return hit.point;
    }
    else return null;
}

Answer

Kay picture Kay · Feb 24, 2015

Hard to say as it always depends on the game logic what and where optimisations are efficient. Basically one or a few ray cast(s) per frame should not be a big deal for PhysX, so I think there are other culprits. Some Suggestions (maybe you have considererd them already):

  • Use compound colliders especially box and sphere s. Rigidbody manual
  • Always attach rigidbodies to moving items
  • Limit the calls to GetBlockCursor to once per Update or even less by calling it every 2nd or 3rd Update only
  • If you need more than one raycast consider using Physics.RaycastAll
  • If the physics engine is to blame for significant frame rate Drops, check whether you can use layers to optimise calculations
  • Use the profiler (provided you have Pro license)