Chapter 4 Physics - more explanation required

Hi,

I need a bit more help than is provided by the current explanation in this chapter.

  1. Why do we create a Ray object and then pass this to Physics.Raycast, which then creates another ray object?

  2. According to Unity’s docs, the first argument passed to Physics.Raycast should be the origin of the ray, with the second argument being the direction. How is this achieved by passing in a ray object and a hit object?

  3. What is the purpose of currentLookTarget? It is set to hit.Point and then it doesn’t appear to be used again.

Its probably obvious to everyone else, but I just don’t understand the logic here.

Thanks in advance

Matt

Hi Matt,

Good question there and this can be a little confusing sometimes due to the out keyword.

What happens here, is that you’re using one of the many available overloads of the Physics.Raycast method (there are a few different method signatures that you can call with this method that alter the way you work with it slightly).

You’re specifically using this method signature:

public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

Where the first parameter is a Ray object, and the second is the out keyword which populates the hitInfo variable with data, if the Raycast was successful (i.e. if the method returns true).

So what happens is:

  • The method you’re calling returns true/false.
  • You create a Ray object (which is actually null to start with) in order to have it available in scope for the out function of the Physics.Raycast method to access it, if the Raycast method is successful and hits something. In other words, the “ray” object is basically just created beforehand so its available for the out bit of the Physics.Raycast method to fill with data)
  • The main point of Physics.Raycast here, is to populate the “ray” variable with hit info (into the “hit” variable). The fact that it returns true/false can also be useful to check in code to see if the raycast hits anything, but you could also probably check if the hit object is null or not to do the same.
  • currentLookTarget is most probably referenced in another script somewhere - its labelled as being the point where the hero looks, so I would assume that there is another script perhaps on the camera, or the player that updates and points the player’s facing direction to this point, so it is most likely updated here in this script, in order for another script to reference it.

Hope that helps clear things up for you! :]

Sean

1 Like