A guide to using BoxCast in Unity

by Michael Sacco Published August 21, 2023

We recently developed an incredible Responsive Smokes asset for Unity. The smoke dynamically grows in your scene. If there is something in the way, then the smoke will get blocked and go a different way.

One method that I looked into for this process was BoxCast().

I ended up using SphereCast() for this specific scenario. But, I wrote this article to help out any beginner game developers who want to learn about BoxCast(). So, what is BoxCast and how does it work?

When you use BoxCast(), you can imagine that you create a Box at the start position. Then, you drag that box through space to the end position. If it hits anything, it tells you.

That’s just the tip of the iceberg. By the end of this article, you will understand what BoxCast does. You will have some code examples showcasing how to use BoxCast in your project. You will have a useful script to draw a BoxCast using the debug tools. And, you will have some resources to continue learning!

Let’s get started.

Key Takeaways

  • To sweep a box through your scene and get collision data for that box, use BoxCast.
  • You need to provide the box dimensions and the length of the sweep.
  • If BoxCast hits something, it returns true.
  • If you want more information about the hit, use the RaycastHit out parameter.

This is a series on Unity Physics. We recommend reading the series in order.

  1. Unity Physics
  2. Unity Collision Detection
  3. Character Controller and Input Systems
  4. Rigidbody Mass in Unity
  5. How to add Friction to a Rigidbody
  6. Cylinder Collider in Unity
  7. Box Collider in Unity
  8. Box Cast in Unity
  9. Sorting Layers
  10. Get the distance between two objects
  11. How to normalize a vector

Usage

  • In 2D games, use Physics2D.BoxCast().
  • In 3D games, use Physics.BoxCast().

I put together a basic example of using each method.

In both examples, you create a BoxCast starting at the origin, then sweep that box 1 unit along the x axis.

Physics2D.BoxCast(Vector2.zero, Vector2.one, 0f, Vector2.right, 1f);
Physics.BoxCast(Vector3.zero, Vector3.one, Vector3.right, Quaternion.identity, 1f);

Learn more about these methods with Unity’s documentation.

What does BoxCast do?

BoxCast creates a 2D or 3D box. Then, it sweeps that box through space. As the box moves through space, Unity looks for collisions. If the box hits anything, the method returns true.

  • Caution: If a collider is already inside of the box when BoxCast starts, BoxCast ignores it. Consider using Physics.OverlapBox() instead.

What parameters does BoxCast offer?

There are six main options when using BoxCast. You get all these options in both the 2D and 3D variants.

  1. The start position
  2. The box size
  3. The box orientation
  4. The direction of the sweep
  5. The distance of the sweep
  6. The list of layers you want to include

Code Example

Imagine that you have a 2D character defined by a box collider. The player provides the input to move this character one unit to the right.

Before you move the character, you want to check: Is there something in the way? Here’s how:


using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
  public BoxCollider2D characterCollider;
  void Update()
  {
    bool doMoveRight = Input.GetKeyDown(KeyCode.D);
    if (doMoveRight)
    {
      if (
        Physics2D.BoxCast(
          characterCollider.bounds.center,
          characterCollider.size,
          0f,
          Vector2.right,
          1f
        )
      )
      {
        Debug.Log("The BoxCast hit something! Don't move.");
      }
      else
      {
        transform.Translate(Vector3.right);
      }
    }
  }
}

Visualize a BoxCast

  1. Copy and paste this component into a new script in your project.
  2. Add the component onto the object you want to visualize the BoxCast for
  3. Set the object scale and max distance
using UnityEngine;

[ExecuteAlways]
public class VisualizeBoxCast : MonoBehaviour
{
  public float maxDistance = 1f;
  void Update()
  {
    if (
      Physics.BoxCast(
        transform.position,
        transform.lossyScale * 0.5f,
        transform.forward,
        Quaternion.identity,
        maxDistance
        )
      )
      {
        Debug.Log("The BoxCast hit something!");
      }
    }
    
    private void OnDrawGizmos()
    {
      DrawBoxCast(
        transform.position,
        transform.position + maxDistance * transform.forward,
        transform.lossyScale,
        transform.rotation
      );
    }
    
    void DrawBoxCast(Vector3 start, Vector3 end, Vector3 size, Quaternion rotation){
      Gizmos.color = Color.green;
      
      // Cache the Gizmos matrix.
      Matrix4x4 currentMatrix = Gizmos.matrix;
      
      // Draw Cubes
      Gizmos.matrix = Matrix4x4.TRS(start, rotation, size);
      Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
      Gizmos.matrix = Matrix4x4.TRS(end, rotation, size);
      Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
      
      // Draw Connecting Lines
      Vector3 x = Vector3.right * size.x * 0.5f;
      Vector3 y = Vector3.up * size.y * 0.5f;
      Vector3 z = Vector3.forward * size.z * 0.5f;
      Gizmos.matrix = Matrix4x4.TRS(start, rotation, Vector3.one);
      Gizmos.DrawRay(Vector3.zero - x - y - z, Vector3.forward * maxDistance);
      Gizmos.DrawRay(Vector3.zero - x + y - z, Vector3.forward * maxDistance);
      Gizmos.DrawRay(Vector3.zero + x - y - z, Vector3.forward * maxDistance);
      Gizmos.DrawRay(Vector3.zero + x + y - z, Vector3.forward * maxDistance);
      
      // Reset the Gizmos matrix.
      Gizmos.matrix = currentMatrix;
    }
}

Further Reading

If you want to continue learning about BoxCast and physics in Unity, I got you. I compiled some lightweight further reading.

Be sure to read Unity’s official documentation on Physics2D.BoxCast() and Physics.BoxCast():

After that, you should read our article on Collider Interactions in Unity:

/blog/collider-interactions-in-unity

Build your game more quickly

The best way to build your game? Use our assets. Don’t make the mistake of trying to build everything from scratch. AAA studios are able to make amazing games because they have a huge team working on their projects. You don’t have the budget for a huge team, but you do have the budget for our free assets. And, if you start earning money from you game, you can level up your project and invest in our premium assets for Unity.

Free download: Indie Game Marketing Checklist

Download now

Category

unity basics

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    A lightweight procedural skybox ideal for semi-stylized projects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Drag-and-drop ready-to-use ambient, impact, and spell particle effects.
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free