Menu
CoddyTech

OverlapSphere and SphereCast

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 38 of 63.

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

Arm the cannon with a wide beam. The Beam script sits on the Cannon, and the Inspector gives it a radius of 0.5 and a range of 12. The left and right arrows turn the cannon.

  • When Space is pressed, sweep a sphere of radius forward from the cannon, range units long.
  • If it hits something, log Hit Pole with the name of what it hit, and destroy that object.
  • If it hits nothing, log Miss.

The thin Pole stands a little to the side of the cannon's centre line. Press Play and fire, 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.
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay