Get Your Personalized Game Dev Plan Tailored tips, tools, and next steps - just for you.

A guide to using BoxCast in Unity

Posted by Gemma Ellison
./
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.

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.

Create a free account, or log in.

Gain access to free articles, game development tools, and game assets.