Unity Raycast2d

Posted on  by 



The normal vector of a surface is the vector that points outward perpendicularly at a given point on that surface. This vector can be useful in raycasting as a way to determine reflections or ricochets from projectiles or to align a character so that it stands upright on the surface. Unity Raycast 2D, firing a laser beam from a point in a certain direction and detecting the colliders 2D through the way, helps us in different ways. It’s useful to: Check if the player is grounded. It's a pretty common requirement in game development to need to know if a particular character or object is on the ground. For instance, your player may only be able to jump, attack, or interact while they are on the ground. A common way to check this is to use a Raycast, which essentially allows you to detect the d.

  1. Unity Raycasthit
  2. Unity Raycast Ignore Layer
  3. Unity Raycasthit2d
  4. Unity Raycast 2d Out Hit
  5. Unity Raycast

Parameters

ParameterDetails
originThe starting point of the ray in world coordinates
directionThe direction of the ray
maxDistanceThe max distance the ray should check for collisions
layerMaskA Layer mask that is used to selectively ignore Colliders when casting a ray.
queryTriggerInteractionSpecifies where this query should hit Triggers.

Physics Raycast

This function casts a ray from point origin in direction direction of length maxDistance against all colliders in the scene.

The function takes in the origindirectionmaxDistance and calculate if there is a collider in front of the GameObject.

For example, this function will print Hello World to the console if there is something within 10 units of the GameObject attached to it:

Physics2D Raycast2D

You can use raycasts to check if an ai can walk without falling off the edge of a level.

In this example the direction is right. The variable raycastRightPart is the right part of the character, so the raycast will happen at the right part of the character. The distance is 0.6f times the height of the character so the raycast won't give a hit when he hits the ground that is way lower than the ground he is standing on at the moment. Make sure the Layermask is set to ground only, otherwise it will detect other kinds of objects as well.

RaycastHit2D itself is a structure and not a class so hit can't be null; this means you have to check for the collider of a RaycastHit2D variable.

Encapsulating Raycast calls

Having your scripts call Raycast directly may lead to problems if you need to change the collision matrices in the future, as you'll have to track down every LayerMask field to accommodate the changes. Depending on the size of your project, this may become a huge undertaking.

Encapsulating Raycast calls may make your life easier down the line.

Looking at it from a SoC principle, a gameobject really shouldn't know or care about LayerMasks. It only needs a method to scan its surroundings. Whether the raycast result returns this or that shouldn't matter to the gameobject. It should only act upon the information it receives and not make any assumptions on the environment it exists in.

One way to approach this is to move the LayerMask value to ScriptableObject instances and use those as a form of raycast services that you inject into your scripts.

This allows you to make a number of raycast services, all with different LayerMask combinations for different situations. You could have one that hits only ground colliders, and another that hits ground colliders and one way platforms.

Raycast

If you ever need to make drastic changes to your LayerMask setups, you only need to update these RaycastService assets.

Further reading


Hey, if you didn't already know, I'm currently working on an open world stealth exploration game called Farewell North in my spare time, which is available to wishlist on Steam!

Related Posts

Animating Rotations through Code in UnitySynchronizing Idle, Walk and Run animations with a NavMeshAgent in UnitySiren Song, Devlog #3: But With More DogsUnity: Working with Custom HLSL Functions in Shader GraphUnity: Accessing Private and Protected Fields from the Inspector

Unity Raycasthit

It’s a pretty common requirement in game development to need to know if a particular character or object is on the ground. For instance, your player may only be able to jump, attack, or interact while they are on the ground.

A common way to check this is to use a Raycast, which essentially allows you to detect if any physics bodies exist within an invisible line - the Raycast itself being that line.

In this post, I’ll show you how to use Raycasts to detect if an object is on the ground. For the purposes of this post, ground refers to GameObjects that are on the Ground layer and have a Collider attached to them. I’ll be writing from the perspective of a Player object that represents a character, but the same technique works for any GameObject.

Setup

The first thing we’ll need to do is add a public LayerMask to our player script. LayerMasks allow us to filter collisions based on the colliding body’s Layer, meaning we can limit our RayCast to search only for objects on the Ground layer.

In the player script, add the following:

Now in the Unity editor, select your player and set the Ground Layer property like so:

Again, this post assumes you have a GroundLayer setup and all your ground objects are on this Layer. Adjust to suit your needs as necessary.

Using Raycasts

Unity Raycast Ignore Layer

With the LayerMask ready to go, we can now write our logic to determine if the player is on the ground.

In the same player script, we’ll add an IsGrounded function that performs the logic and returns a boolean - true if the player is on the ground, false otherwise.

What we’re doing here is creating a Raycast using Physics2d, in a downward direction using Vector2.down (shorthand for Vector2(0, -1.0f)). We limit the Raycast to the groundLayer so that only Ground objects are detected, preventing us from colliding with our own physics body or that of anything else beneath us.

You’ll also notice we limit the distance of the Raycast, which is important because if the player jumps in the air, there would still technically be groundLayer objects beneath them - we’re interested only if it’s directly beneath them. It’s important to note that the value used (1.0f in this case) is going to vary based on your setup, so you’ll want to tweak and debug to determine what value works for your game.

Once the Raycast is complete, we check if there were any collisions using hit.collider != null. If the collider is not null, that means there was an object found and we are on the ground.

Now you’ll be able to perform checks in the rest of your player script to determine if the player is on the ground, and act accordingly. For instance, you could check if the player is on the ground before allowing them to jump:

Debugging

A useful trick for debugging Raycast checks if to use the DrawRay function of Debug. This allows you to visualize the Raycasts by drawing them out on the scene editor in Unity - not in the actual game itself.

Unity Raycasthit2d

To add DrawRay to the IsGrounded function above, you would do something like the following:

Unity Raycast 2d Out Hit

Now in the Scene editor of Unity, you’ll see a little green line on your player like the image below, allowing you to validate the Raycast:

This is handy because you can monitor your Raycast as your player moves around, and ensure that it’s size and positioning is correct.

Unity Raycast

Let me know if this post was helpful on Twitter @kylewbanks or down below!




Coments are closed