I learn unity tutorial survival shooter and I see following code in Assets/_Complete-Game/Scripts/Player/PlayerMovement.cs
if (Physics.Raycast(camRay, out floorHit, camRayLength, floorMask))
the #Raycast define is:
public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance, int layerMask)
I have 2 questions:
- why should I set camRayLength, if I set it with very large number for ex 999999, what will happen?
- what value should i set, in the unity tutorial code, the maxDistatnce is 100, why it’s not 1000 or 10000
Think of raycasts like an infinitely thin lightsaber beam, which you can adjust the length of. It’s useful to set a max length of the ray because of optimization reasons, hit info will not be generated if the ray does not hit anything and if the target(or targets) are too far away(> maxDistance) then the ray won’t hit.
There’s simply no need to query at a distance of say Mathf.Infinity when you really only need the information within 100 units. In your particular example it looks like the ray is used for ground detection, so a ray of 100 units in length sounds pretty good. If it’s too short the gravity acceleration might become too great and the ray fails to register in time. If the ray is longer than needed, you end up generating hit info waaaay before it’s necessary, and on top of that you’ll also perform calculations on said info(checking distance to ground in your case and maybe even retrieving the ground angle).