Physics
TypeStatic class
NamespaceUnityEngine
2D versionPhysics2D

Physics

The Physics class lets you ask questions about the physics world: "If I shoot a line from here, what does it hit?" or "What's inside this sphere?". It also holds global settings such as gravity.

A raycast is a laser pointer. You shine it from a point in a direction, and it tells you the first thing it lands on, how far away it is, and the exact spot. A SphereCast is the same but with a thick beam, like rolling a ball down a hallway. An Overlap check is dropping an invisible bubble somewhere and asking "who's inside?"

Static Properties

NameTypeDescription
gravityVector3Gravity for all Rigidbodies. Default (0, -9.81, 0).

Static Methods

MethodReturnsDescription
Raycast(origin, direction, out RaycastHit hit, maxDistance, layerMask)boolShoots a thin line. true if it hit something; details go into hit.
Raycast(Ray ray, out RaycastHit hit, maxDistance)boolSame, using a Ray (e.g. from Camera.ScreenPointToRay).
RaycastAll(...)RaycastHit[]Everything along the line, not sorted by distance.
SphereCast(origin, radius, direction, out hit, maxDistance)boolA thick ray. Good for ground checks and "would I fit?".
Linecast(start, end, out hit)boolIs anything between two points? (line of sight)
OverlapSphere(position, radius, layerMask)Collider[]All colliders inside a sphere. Explosions, auras.
OverlapBox(center, halfExtents, rotation, layerMask)Collider[]All colliders inside a box.
CheckSphere(position, radius, layerMask)boolIs anything inside? Cheapest check.
IgnoreCollision(a, b, ignore = true)voidMake two specific colliders pass through each other.

RaycastHit (the result)

MemberDescription
hit.colliderThe collider that was hit.
hit.transformIts Transform (the Rigidbody's, if it has one).
hit.pointExact world position of the hit.
hit.normalDirection the surface faces at that point.
hit.distanceHow far from the origin.
originCollider (wall)directionnot checked past the first hithit.normalhit.pointhit.distancemaxDistance
What Physics.Raycast(origin, direction, out RaycastHit hit, maxDistance) measures. The ray stops at the first collider; hit.normal points out of the surface, which is the direction to spawn impact effects or bounce.

Layer masks: only hit certain things

The layerMask parameter is a filter. Create one in code with LayerMask.GetMask, or better, expose a LayerMask field and pick layers from a dropdown in the Inspector.

[SerializeField] private LayerMask groundLayers;             // pick in Inspector
int enemyMask = LayerMask.GetMask("Enemy", "Destructible");  // or build in code

Code Samples

Hitscan gun

using UnityEngine;

public class HitscanGun : MonoBehaviour
{
    [SerializeField] private Camera cam;
    [SerializeField] private float range = 100f;
    [SerializeField] private LayerMask hitLayers;

    void Update()
    {
        if (!Input.GetButtonDown("Fire1")) return;

        // Shoot from the center of the screen.
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
        if (Physics.Raycast(ray, out RaycastHit hit, range, hitLayers))
        {
            Debug.Log("Hit " + hit.collider.name + " at " + hit.point);
            if (hit.collider.TryGetComponent(out Health h)) h.TakeDamage(25);
        }
    }
}

Ground check

[SerializeField] private LayerMask groundLayers;

bool IsGrounded()
{
    // A short line straight down from slightly above the feet.
    Vector3 origin = transform.position + Vector3.up * 0.1f;
    return Physics.Raycast(origin, Vector3.down, 0.2f, groundLayers);
}

Explosion that damages everything nearby

void Explode(Vector3 center, float radius)
{
    Collider[] hits = Physics.OverlapSphere(center, radius);
    foreach (Collider c in hits)
    {
        if (c.attachedRigidbody != null)
            c.attachedRigidbody.AddExplosionForce(700f, center, radius);
    }
}

Click on objects with the mouse

if (Input.GetMouseButtonDown(0))
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out RaycastHit hit))
    {
        Debug.Log("Clicked " + hit.collider.gameObject.name);
    }
}

What happens at runtime

  1. A raycast is answered immediately, on the same line of code. It doesn't wait for the next physics step.
  2. It checks against the colliders' positions as of the last physics step. If you moved a Transform this frame, the physics world may not know yet (unless Physics.SyncTransforms() is called or auto-sync is on).
  3. Only colliders are checked. Meshes without a collider are invisible to raycasts.
  4. By default, raycasts hit trigger colliders too (controlled by Project Settings > Physics > Queries Hit Triggers, or the QueryTriggerInteraction parameter).

Common Mistakes

See also