I am trying to get my head around Raycasting, after reading some literature, I am at a loss as to why I haven’t seen the Ray being defined in a constructor (in examples I have seen) or in the generic script -
Physics.Raycast(Vector3 origin, Vector3.forward, RaycastHit hitInfo, float distance, int LayerMask);
I don’t know how to specify which one of my many potential projectiles should be used in the code above. Maybe I am missing a line of code.
Ray ray = new Ray(transform.position, transform.forward);
I have also seen the above and used in videos, but again haven’t spotted how to define what should be cast. Explaining how to do this would be really helpful, as in my current project the player has a variety of different ranged attacks.
You don’t need to specifie the Ray as a variable, but if you do so, you can change the direction via scripting, the Vector3.forward (Vector3(0,0,1)) means that the ray will pass trough that specific point, so that’s basically it’s direction.
If you want to define a “Ray” variable, then instead of the origin and direction, you use the variable
The direction, there’s only one ray/direction, and because the ray need to cross the specified point (in this case Vector3.forward), it’s direction is set
A Ray is nothing more than a two-vector structure, one vector representing the origin (position) of the ray, the other representing it’s direction. It helps to think of Rays in the same way you’d think of Vectors or numbers, they’re just a data type.
The Raycast method has several variants, so you can use whichever is most convenient to you. Some of these variants (called ‘overloads’) don’t take a Ray parameter, because they take two vectors (origin and direction) instead. Whichever way you choose to handle the data, the information is all there for the Raycast to do its thing.
Now, there are also some overloads where you have to supply less information than in others. In those cases, you should keep in mind that any parameter you aren’t specifying yourself is probably being given a default value. That may or may notbe ok, depending on what you want to accomplish.