Menu
CoddyTech

OverlapSphere and SphereCast

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 40 of 71.

A ray asks about a line. Physics.OverlapSphere(center, radius) asks about a ball-shaped region: it returns an array of every collider that touches a sphere at center, with no direction and no distance. This bomb destroys every crate within 3 units when it goes off:

void Explode()
{
    Collider[] hits = Physics.OverlapSphere(transform.position, 3f);
    foreach (Collider c in hits)
    {
        if (c.CompareTag("Crate"))
        {
            Destroy(c.gameObject);
        }
    }
    Destroy(gameObject);
}

The array holds everything in reach: the floor, the walls and the bomb's own collider, because overlap tests do not skip the collider they start inside. That is why the loop checks the tag before acting. Each collider's attachedRigidbody is the Rigidbody it belongs to, or null for static things such as the floor.

Physics.SphereCast(origin, radius, direction, out hit, maxDistance) is a thick ray: it sweeps a sphere along the line and reports the first collider the sphere would bump into. A boulder of radius 1 rolling toward a gap 1.5 wide between two posts asks it whether it fits: a thin ray down the middle of the gap hits nothing, while the sphere cast hits a post. Like a ray, a sphere cast skips colliders it already touches where it starts.

challenge icon

Challenge

Medium

Give the cannon a wide beam with Physics.SphereCast.

  1. On Space, sweep a sphere: Physics.SphereCast(transform.position, radius, transform.forward, out RaycastHit hit, range).
  2. On a hit, log "Hit " + hit.collider.name (the first shot logs Hit Pole) and destroy that object.
  3. On a miss, log Miss.

Press Play and fire three times: the Pole goes, then the Crate, then Miss. Then Check.

Try it yourself

using UnityEngine;

public class Beam : MonoBehaviour
{
    public float radius = 0.5f;
    public float range = 12f;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // Sweep a sphere of radius forward: destroy the first thing it hits.
        }
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground