Raycast 2d Unity is one of the most useful tools for detecting objects in a 2D game. If you have ever needed to check whether an enemy is in front of the player, detect the ground below a character, or find out which object a weapon is hitting, you have probably needed a raycast.
In Unity, the easiest way to perform a 2D raycast is with Physics2D.Raycast().
A raycast does not move an object or create a visible laser. It simply sends an invisible ray from one position in a particular direction and checks whether that ray hits a 2D collider.

For example:
Player
|
|---------------------------> Enemy
Ray
If the ray reaches the enemy’s Collider2D, Unity can return information about that object.
In this guide, I’ll show you how to use Raycast 2d unity from the basics and then build it into practical gameplay examples such as shooting, ground detection, object interaction, line of sight, LayerMasks, and debugging.
Note: This tutorial focuses on Unity’s 2D physics system and
Physics2D.Raycast(). If you’re working with 3D objects and colliders, you would normally usePhysics.Raycast()instead.
What Is Raycast 2d in unity?

The easiest way to understand a raycast is to think of it as an invisible laser.
You give Unity:
- A starting position
- A direction
- A maximum distance
- Optionally, a LayerMask to control what can be detected
Unity then checks the 2D physics scene for colliders along that path.
For example, suppose the player needs to know whether an enemy is directly in front of them.
Instead of checking every enemy in the scene, you can send a ray forward:
Player
|
|-------------------->
| |
| Enemy
If the ray hits the enemy’s Collider2D, you have your answer.
This makes Unity 2d raycast useful for many common gameplay systems:
- Enemy detection
- Shooting
- Ground checks
- Wall detection
- Object interaction
- Line-of-sight detection
- Simple AI vision
- Checking obstacles
The important part is that a raycast is a query. It asks the physics system whether something exists along a particular path.
Physics2D.Raycast vs Physics.Raycast
If you’re new to Unity, it is easy to confuse these two methods:
Physics.Raycast()
and
Physics2D.Raycast()
They belong to different physics systems.
| Method | Physics system |
|---|---|
Physics.Raycast() | 3D |
Physics2D.Raycast() | 2D |
If your game uses components such as:
BoxCollider2D
CircleCollider2D
PolygonCollider2D
Rigidbody2D
you will normally use:
Physics2D.Raycast()
For 3D components such as BoxCollider and Rigidbody, you would use Physics.Raycast().
This is one of the first things I check when a Unity raycast isn’t detecting an object: am I using the correct physics API?
How to Use Raycast 2d Unity
Let’s start with a simple example.
Create a C# script and attach it to a GameObject:
using UnityEngine;
public class RaycastExample : MonoBehaviour
{
[SerializeField] private float rayDistance = 10f;
private void Update()
{
RaycastHit2D hit = Physics2D.Raycast(
transform.position,
Vector2.right,
rayDistance
);
if (hit.collider != null)
{
Debug.Log("Hit: " + hit.collider.name);
}
}
}
That’s enough to perform a basic Raycast 2d Unity check.
The important part is:
Physics2D.Raycast(
transform.position,
Vector2.right,
rayDistance
);
The method takes an origin, direction and distance, with a LayerMask available when you want to filter which colliders can be detected.
Let’s break those parameters down.
Understanding the Raycast Origin
The first parameter tells Unity where the ray should start.
In our example:
transform.position
is used as the origin.
So if the GameObject is here:
Player ●
the ray starts from the player’s position.
You don’t have to use the GameObject’s exact center. In a real game, you might create a separate child object such as:
Player
└── RaycastPoint
and use:
raycastPoint.position
This can be useful when the ray needs to start from a weapon, character’s feet, or another specific position.
Choosing the Raycast Direction
The second parameter controls where the ray travels.
For example:
Vector2.right
casts the ray to the right.
You can also use:
Vector2.left
Vector2.up
Vector2.down
For a custom direction:
Vector2 direction = new Vector2(1f, 0.5f);
If the direction comes from two positions, normalize it before using it:
Vector2 direction =
(target.position - transform.position).normalized;
This is particularly useful for enemy vision and line-of-sight checks.
Setting the Raycast Distance
The third parameter determines how far the ray should check.
float rayDistance = 10f;
Then:
Physics2D.Raycast(
transform.position,
Vector2.right,
rayDistance
);
means:
Start here, travel to the right, and check up to 10 Unity units away.
Keeping the distance limited is usually better than using an unnecessarily large range.
Understanding RaycastHit2D
One of the most important parts of a 2D Raycast Unity implementation is RaycastHit2D.
When the ray hits something, Unity returns a RaycastHit2D containing information about the result.
For example:
RaycastHit2D hit = Physics2D.Raycast(
transform.position,
Vector2.right,
10f
);
if (hit.collider != null)
{
Debug.Log("Object: " + hit.collider.gameObject.name);
Debug.Log("Point: " + hit.point);
Debug.Log("Distance: " + hit.distance);
}
Some useful properties include:
| Property | Purpose |
|---|---|
hit.collider | Collider2D that was detected |
hit.point | Point where the ray hit |
hit.distance | Distance to the hit |
hit.normal | Surface normal at the hit |
hit.rigidbody | Rigidbody2D associated with the collider |
Most of the time, you’ll start with:
hit.collider
because it tells you whether the ray actually detected something.
For example:
if (hit.collider != null)
{
Debug.Log("Detected: " + hit.collider.name);
}
Using LayerMask with Raycast 2d Unity
A raycast does not always need to detect everything.
Imagine your scene contains:
- Player
- Enemy
- Ground
- Bullets
- Background
- Decorations
- Collectibles
If you’re creating an enemy detection system, you probably don’t care about the background or decorative objects.
This is where LayerMask becomes useful.
Create a LayerMask field:
[SerializeField] private LayerMask enemyLayer;
Then pass it to Physics2D.Raycast():
RaycastHit2D hit = Physics2D.Raycast(
transform.position,
Vector2.right,
10f,
enemyLayer
);
if (hit.collider != null)
{
Debug.Log("Enemy detected: " + hit.collider.name);
}
Now you can select the appropriate layers from the Unity Inspector.
Why use a LayerMask?
Without a LayerMask, your question is basically:
Did this ray hit something?
With a LayerMask, you can ask:
Did this ray hit something from the layers I’m interested in?
That makes the detection logic much cleaner.
Layer filtering is also useful for controlling what a Physics2D.Raycast can detect. Unity’s API specifically supports a layerMask parameter for this purpose.
How to Draw Raycast Line in Unity 2D
One of the most common problems with raycasts is that you cannot see them.
The raycast itself is invisible.
When debugging, I usually use:
Debug.DrawRay()
For example:
private void Update()
{
Vector2 origin = transform.position;
Vector2 direction = Vector2.right;
float distance = 10f;
Debug.DrawRay(
origin,
direction * distance
);
RaycastHit2D hit = Physics2D.Raycast(
origin,
direction,
distance
);
if (hit.collider != null)
{
Debug.Log("Hit: " + hit.collider.name);
}
}
This lets you visually check where the ray is going while debugging your game.
How to See Raycast Unity 2D in the Scene
If you’re wondering how to see Raycast Unity 2D, Debug.DrawRay() is usually the quickest solution.
While the game is running:
- Open the Unity Scene view.
- Make sure Gizmos are enabled.
- Select the GameObject containing the script.
- Check the direction of the debug line.
- Check whether the line reaches the object you’re trying to detect.
For example:
Debug.DrawRay(
transform.position,
transform.right * 10f
);
If the line is pointing in the wrong direction, the problem may be your direction vector rather than the raycast itself.
Debug.DrawRay() is mainly useful while developing and debugging. It isn’t a replacement for a visual effect that needs to appear in the final game.
Drawing Only the Raycast Hit Line
Sometimes you don’t want to display the entire ray.
It can be more useful to show only the part between the origin and the object that was hit.
That’s where Debug.DrawLine() helps.
private void Update()
{
Vector2 origin = transform.position;
Vector2 direction = Vector2.right;
float distance = 10f;
RaycastHit2D hit = Physics2D.Raycast(
origin,
direction,
distance
);
if (hit.collider != null)
{
Debug.DrawLine(
origin,
hit.point
);
}
else
{
Debug.DrawRay(
origin,
direction * distance
);
}
}
This makes debugging much easier because you can immediately see whether the ray actually reaches a collider.
If you want a line visible to players in the final game, use something such as a LineRenderer rather than relying on Debug.DrawLine().
Using Raycast Unity 2D for Shooting
A raycast works particularly well for hitscan weapons.
A hitscan weapon doesn’t need to simulate a bullet travelling through the world. When the player shoots, the game immediately checks what is in front of the weapon.
For example:
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
[SerializeField] private Transform shootingPoint;
[SerializeField] private float shootingRange = 10f;
[SerializeField] private LayerMask targetLayer;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Shoot();
}
}
private void Shoot()
{
RaycastHit2D hit = Physics2D.Raycast(
shootingPoint.position,
shootingPoint.right,
shootingRange,
targetLayer
);
if (hit.collider != null)
{
Debug.Log("Shot hit: " + hit.collider.name);
}
}
}
Here the ray starts at:
shootingPoint.position
and travels in:
shootingPoint.right
for the specified shooting range.
This is a good approach for laser weapons, instant guns, and other hitscan-style mechanics.
If your game needs a physical bullet that travels over time, a projectile with a Rigidbody2D may be more appropriate.
Applying Damage After a Raycast Hit
Finding the target is only one part of a shooting system.
After detecting the target, you can call your health or damage system.
For example:
private void Shoot()
{
RaycastHit2D hit = Physics2D.Raycast(
shootingPoint.position,
shootingPoint.right,
shootingRange,
targetLayer
);
if (hit.collider != null)
{
Enemy enemy = hit.collider.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(10);
}
}
}
I prefer keeping the raycast responsible for detection and letting the enemy or health component handle damage.
That separation becomes useful when the project grows because the shooting system doesn’t need to know how an enemy manages health internally.
Using Raycast Unity 2D for Object Interaction
Raycasts can also be used when the player needs to interact with something directly in front of them.
For example:
[SerializeField] private float interactionDistance = 2f;
[SerializeField] private LayerMask interactionLayer;
private void Update()
{
RaycastHit2D hit = Physics2D.Raycast(
transform.position,
transform.right,
interactionDistance,
interactionLayer
);
if (hit.collider != null)
{
Debug.Log(
"Interactive object: " + hit.collider.name
);
}
}
You can build systems like:
- Open door
- Pick up item
- Talk to NPC
- Activate switch
- Read sign
- Interact with machine
- Collect an object
The raycast only answers:
What is in front of me?
Your interaction system can then decide what to do with the detected object.
Unity Raycast 2D for Ground Detection
Ground detection is another common use of a downward raycast.
A simple implementation looks like this:
[SerializeField] private float groundCheckDistance = 0.2f;
[SerializeField] private LayerMask groundLayer;
private bool IsGrounded()
{
RaycastHit2D hit = Physics2D.Raycast(
transform.position,
Vector2.down,
groundCheckDistance,
groundLayer
);
return hit.collider != null;
}
You can then use it when deciding whether the player can jump:
if (IsGrounded())
{
// Allow the player to jump.
}
This is a simple example of a Unity Raycast Down check.
However, there is an important limitation.
A single ray only checks one narrow path.
If your character is wide:
Player
┌─────────┐
│ │
│ ● │ ← one ray
│ | │
└────|────┘
|
Ground
the ray may miss the ground near an edge.
For more reliable character detection, you may eventually want to use a BoxCast, CapsuleCast, or overlap check depending on the shape of your character.
Using Multiple Raycasts in Unity 2D
Sometimes a single ray isn’t enough.
For example, a character controller may need to check several points below the character.
You can cast multiple rays:
[SerializeField] private float rayDistance = 1f;
private void Update()
{
Vector2 origin = transform.position;
Vector2 leftOrigin =
origin + Vector2.left * 0.3f;
Vector2 centerOrigin = origin;
Vector2 rightOrigin =
origin + Vector2.right * 0.3f;
Physics2D.Raycast(
leftOrigin,
Vector2.down,
rayDistance
);
Physics2D.Raycast(
centerOrigin,
Vector2.down,
rayDistance
);
Physics2D.Raycast(
rightOrigin,
Vector2.down,
rayDistance
);
}
Multiple rays can be useful for:
- Character controllers
- Edge detection
- Wall checks
- AI vision
- Custom movement systems
But don’t automatically add more rays just because they seem useful.
If you are checking an area rather than a specific direction, an overlap query or shape cast may be a better fit.
Creating Line of Sight with Raycast Unity 2D
A simple enemy line-of-sight system is another practical use of a 2D raycast.
Suppose an enemy wants to know whether a player is visible.
First calculate the direction:
Vector2 direction =
(player.position - transform.position).normalized;
Then calculate the distance:
float distance =
Vector2.Distance(
transform.position,
player.position
);
Now cast the ray:
[SerializeField] private Transform player;
[SerializeField] private LayerMask obstacleLayer;
private void CheckLineOfSight()
{
Vector2 origin = transform.position;
Vector2 direction =
(player.position - transform.position).normalized;
float distance =
Vector2.Distance(
transform.position,
player.position
);
RaycastHit2D hit = Physics2D.Raycast(
origin,
direction,
distance,
obstacleLayer
);
if (hit.collider == null)
{
Debug.Log("Player is visible");
}
else
{
Debug.Log("Something is blocking the player");
}
}
The important part is the LayerMask.
Here, the ray is only looking for obstacles.
If it doesn’t hit an obstacle before reaching the player, there is a clear line of sight.
This can be useful in:
- Top-down games
- Stealth games
- Enemy AI
- Tower defense
- 2D shooter games
For more advanced AI, you may also need a field-of-view angle, distance checks, and additional gameplay rules.
Using Physics2D.RaycastAll for Multiple Hits
Sometimes you don’t want just the first detected object.
Imagine several colliders are positioned along the same ray:
Player ---> Enemy ---> Wall ---> Object
If you need information about multiple hits, use:
RaycastHit2D[] hits = Physics2D.RaycastAll(
transform.position,
Vector2.right,
10f
);
foreach (RaycastHit2D hit in hits)
{
Debug.Log("Hit: " + hit.collider.name);
}
RaycastAll is useful when multiple objects along the ray matter.
For a normal question such as:
Is there something directly in front of me?
the standard:
Physics2D.Raycast()
is usually the simpler option.
Unity also provides overloads that can work with a ContactFilter2D and result arrays/lists when you need more control over filtering or frequent queries.
Common Raycast Unity 2D Problems
If your Raycast Unity 2D code isn’t detecting anything, don’t immediately assume the API is broken.
There are a few common things worth checking.
1. The Object Doesn’t Have a Collider2D
A raycast needs a collider to detect.
Check that the target has an appropriate component, such as:
BoxCollider2D
CircleCollider2D
CapsuleCollider2D
PolygonCollider2D
2. You’re Using the Wrong Physics API
For 2D colliders:
Physics2D.Raycast()
For 3D colliders:
Physics.Raycast()
Using the 3D API for a 2D physics setup is a common mistake.
3. The Ray Is Pointing the Wrong Way
Use:
Debug.DrawRay(
transform.position,
transform.right * 10f
);
Then look at the Scene view.
You may find that the ray is going somewhere completely different from what you expected.
4. The Ray Is Too Short
If your object is five units away and your ray only travels two units:
Physics2D.Raycast(
origin,
direction,
2f
);
it won’t reach the object.
Temporarily increase the distance and test again.
5. The LayerMask Is Filtering Out the Object
This is another very common issue.
For testing, remove the LayerMask temporarily:
RaycastHit2D hit = Physics2D.Raycast(
origin,
direction,
10f
);
If this works but the LayerMask version doesn’t, check the object’s layer and your LayerMask configuration.
6. The Ray Starts Inside a Collider
This one is easy to overlook.
If the ray starts inside a collider, the result can behave differently from what you might expect because the ray is already inside that collider. Unity documents this behavior for Physics2D.Raycast.
If your raycast keeps detecting an unexpected collider, check the exact position of the ray’s origin.
Raycast vs Linecast in Unity 2D
Physics2D.Raycast() and Physics2D.Linecast() are related, but they are useful in slightly different situations.
A raycast starts at one point and travels in a direction for a distance:
Physics2D.Raycast(
origin,
direction,
distance
);
A linecast checks between two positions:
Physics2D.Linecast(
startPoint,
endPoint
);
For example, if you already have:
Enemy ---------------- Player
obstacle?
and simply want to know whether something is blocking the path between those two positions, a linecast can be convenient.
Use a raycast when your logic naturally has:
origin + direction + distance
Use a linecast when you naturally have:
start point + end point
Raycast vs Overlap Checks in Unity 2D
A ray isn’t always the right physics query.
The best option depends on what you’re trying to detect.
| Requirement | Suitable query |
|---|---|
| Detect something directly ahead | Raycast |
| Check directly below player | Raycast |
| Check between two points | Linecast |
| Detect objects around a point | OverlapCircle |
| Detect objects inside an area | OverlapBox |
| Check a larger character shape | BoxCast / CapsuleCast |
For example, if your question is:
Is there something directly in front of me?
A raycast makes sense.
But if the question is:
Which enemies are within five units around me?
an overlap query is usually a better representation of that problem.
Choosing the right physics query can make the code easier to understand and avoid unnecessary raycasts.
How to Optimize Physics2D.Raycast
A single raycast is generally not something I would optimize prematurely.
The bigger concern is when a system starts performing a large number of physics queries every frame.
Here are a few practical things to keep in mind.
Use a LayerMask
If your ray only needs to detect enemies, don’t make it consider unrelated layers.
Physics2D.Raycast(
origin,
direction,
distance,
enemyLayer
);
Keep the Ray Distance Reasonable
If your interaction distance is two units, there is usually no reason to check 100 units.
Don’t Run Detection When You Don’t Need It
For example, a shooting raycast can run when the player shoots:
if (Input.GetMouseButtonDown(0))
{
Shoot();
}
There is no need to perform the shooting raycast every frame.
Don’t Use RaycastAll Without a Reason
If you only need the first relevant hit, use:
Physics2D.Raycast()
instead of:
Physics2D.RaycastAll()
For systems that perform many physics queries frequently, Unity also provides result-array/list overloads that can help control allocations.
The main rule is simple: optimize based on actual usage and profiling rather than assuming every raycast is expensive.
A Complete Raycast Unity 2D Example
If you want a small script to experiment with, this is a good starting point:
using UnityEngine;
public class Simple2DRaycast : MonoBehaviour
{
[SerializeField] private float distance = 10f;
[SerializeField] private LayerMask targetLayer;
private void Update()
{
Vector2 origin = transform.position;
Vector2 direction = transform.right;
Debug.DrawRay(
origin,
direction * distance
);
RaycastHit2D hit = Physics2D.Raycast(
origin,
direction,
distance,
targetLayer
);
if (hit.collider != null)
{
Debug.Log(
$"Hit {hit.collider.name} at {hit.point}"
);
}
}
}
How to test this script
Create a simple test scene:
- Create a 2D GameObject.
- Add the
Simple2DRaycastscript. - Create another 2D object in front of it.
- Add a
Collider2Dto the target. - Put the target on a dedicated layer.
- Select that layer in
Target Layer. - Press Play.
- Look at the Scene view to see the debug ray.
Once the basic example works, start modifying it.
Try changing:
Vector2.right
to:
Vector2.down
or:
Vector2.left
Then experiment with the LayerMask and distance.
This is often a better way to understand raycasts than starting with a complicated gameplay system.
Final Thoughts on Raycast Unity 2D
Once you understand Raycast Unity 2D, many 2D gameplay systems become easier to build.
The basic idea is simple:
Physics2D.Raycast(
origin,
direction,
distance
);
From there, you can add the pieces you need:
RaycastHit2Dto inspect what was detectedLayerMaskto control which objects can be detectedDebug.DrawRay()to visualize the rayDebug.DrawLine()to show the actual hit pathRaycastAll()when multiple hits are required- Linecasts when you already have two positions
- Overlap checks when you need area-based detection
The important thing isn’t to use a raycast everywhere.
Use it when your gameplay question is something like:
“Is there an object along this path?”
That’s where a raycast fits naturally.
Once you are comfortable with Unity Raycast 2D, you can use the same basic idea for shooting, enemy vision, ground detection, interaction systems, wall checks, and many other 2D mechanics.
If you’re looking for the 3D version, that’s a separate topic because it uses Unity’s 3D physics API, Physics.Raycast().
Frequently Asked Questions About Raycast Unity 2D
What is Raycast Unity 2D?
Raycast Unity 2D is a physics query that sends an invisible ray through the 2D scene and checks whether it intersects a Collider2D. Unity provides this functionality through Physics2D.Raycast().
How do I use Raycast Unity 2D?
The basic syntax is:
RaycastHit2D hit = Physics2D.Raycast(
origin,
direction,
distance
);
Then check:
if (hit.collider != null)
{
// Something was detected.
}
What is Physics2D.Raycast used for?
Physics2D.Raycast() can be used for object detection, shooting, ground checks, wall detection, interaction systems, line-of-sight checks, and other gameplay mechanics. Unity’s documentation describes raycasts as a way to detect colliders along a particular path.
What is the difference between Raycast Unity 2D and Raycast Unity 3D?
2D games generally use:
Physics2D.Raycast()
while 3D games generally use:
Physics.Raycast()
The APIs belong to Unity’s separate 2D and 3D physics systems.
How do I see a Raycast in Unity?
Use:
Debug.DrawRay(
transform.position,
transform.right * 10f
);
Then run the game and look at the Unity Scene view with Gizmos enabled.
How do I draw a Raycast line in Unity 2D?
You can use Debug.DrawRay() to draw the complete ray:
Debug.DrawRay(
origin,
direction * distance
);
Or use Debug.DrawLine() if you want to draw from the origin to the actual hit point.
How do I ignore a layer with Unity 2D Raycast?
The usual approach is to control which layers the raycast can detect with a LayerMask:
[SerializeField] private LayerMask targetLayer;
Then pass it to:
Physics2D.Raycast(
origin,
direction,
distance,
targetLayer
);
Can I use Raycast Unity 2D for shooting?
Yes. Physics2D.Raycast() is useful for hitscan-style weapons where the target should be detected immediately instead of simulating a physical projectile.
Can I use Raycast for ground detection?
Yes. A downward raycast can check whether a collider exists below the player:
Physics2D.Raycast(
transform.position,
Vector2.down,
groundCheckDistance,
groundLayer
);
For larger characters, a shape cast or overlap check may provide more reliable results.
What is RaycastHit2D used for?
RaycastHit2D contains information about the raycast result, including the detected collider, hit position, distance and surface normal.
Should I use Raycast or OverlapCircle?
Use a raycast when you need directional detection.
Use an overlap query when you need to detect objects inside an area.
For example:
Specific direction → Raycast
Area around player → OverlapCircle
Between two points → Linecast
What should I use: Physics.Raycast or Physics2D.Raycast?
For 2D colliders, use:
Physics2D.Raycast()
For 3D colliders, use:
Physics.Raycast()
Choosing the correct physics API is important when troubleshooting raycast detection.

Pingback: Unity Raycast Tutorial: How to Raycast, Detect Objects and Draw Ray Lines