# The Physics Behind Raycasting in Unity

Raycasting in Unity allows the detection of intersections between a ray and game objects in the scene. It's a vital technique, frequently used for character line of sight, shooting mechanics, or object detection. The Unity Engine provides both 2D and 3D raycasting through its physics system. This tutorial covers the foundational aspects of raycasting in both dimensions, with concise code examples to illustrate the concepts.

## 1. Basics of Raycasting

• A ray in the context of Unity is defined by a starting point and a direction. When this ray is cast, it ´travels´ in its direction, detecting any objects it intersects.

2D Raycasting:

``````Vector2 rayOrigin = new Vector2(1, 1);
Vector2 rayDirection = new Vector2(1, 0);
float rayLength = 10f;

RaycastHit2D hitInfo = Physics2D.Raycast(rayOrigin, rayDirection, rayLength);

if (hitInfo.collider != null)
{
Debug.Log("Hit: " + hitInfo.collider.name);
}``````

3D Raycasting:

``````Vector3 rayOrigin = new Vector3(1, 1, 1);
Vector3 rayDirection = new Vector3(1, 0, 0);
float rayLength = 10f;

RaycastHit hitInfo;
bool hasHit = Physics.Raycast(rayOrigin, rayDirection, out hitInfo, rayLength);

if (hasHit)
{
Debug.Log("Hit: " + hitInfo.collider.name);
}``````

## 2. Diving Deeper: The Structure of 'RaycastHit'

• When raycasting successfully detects an object, it returns information in a structure. For 2D it's 'RaycastHit2D', and for 3D it's 'RaycastHit'.

Common properties include:

• 'collider': The Collider the ray hit.
• 'point': The point in the world where the ray hit the collider's surface.
• 'distance': The distance from the ray's origin to the hit point.

## 3. Layer Masks: Filtering Raycast Results

• It often becomes necessary to limit which objects a ray can hit. Unity offers layer masks for this purpose.

2D Implementation:

``````int layerMask = 1 << 8;  // Assuming objects to be hit are on layer 8
RaycastHit2D hitInfo = Physics2D.Raycast(rayOrigin, rayDirection, rayLength, layerMask);``````

3D Implementation:

``````int layerMask = 1 << 8;  // Assuming objects to be hit are on layer 8
bool hasHit = Physics.Raycast(rayOrigin, rayDirection, out hitInfo, rayLength, layerMask);``````