Unity Raycast2d



Raycast2d

  1. Unity Raycast2d
  2. Raycast Hit 2d
  3. Unity Raycast 2d

I've looked around for other solutions, such as Unity - Raycast not hitting to BoxCollider2D objects, but when I change my code to the one used in that answer: RaycastHit2D hit = Physics2D.Raycast( Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.back ). Lets start with, you should not be casting a ray in every frame in the update.Don't know how the Engine may react. You should start by setting a condition to cast the ray, for example when you press a key or similar. Unity Raycast2D only shoots like 1 unit. Unity2D preventing character from multi-jumping. Unity Raycast always returning true. How do I remedy.

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!
  1. Unity Raycast works only once-Ignores NavMeshAgents. Hot Network Questions Should I convince my advisor that thesis work is not finished yet Remove paths from list if.
  2. Shoot ray unity; unity raytrace; unity raycast2d; raycast object unity; unity raytraceing; how to shoot a ray at a vector3; unit ray; how to display a raycast in unity; c# raycast example unity; unity 3d raycasting; unity make ray from object; unit test raycasrt object in unity; unity raycats; on raycast enter unity; raycaster unity; how to.
Layer

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

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

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.

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

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:

Unity Raycast2d

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

Let me know if this post was helpful on Twitter @kylewbanks or down below!
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

Frequently in Unity you’ll see OnMouseDown used to detect clicks on GameObjects. This works fine but it requires a script on the GameObject itself, and may require synchronization within the game when there are many clickable objects.

Another method, and the one we’ll be going over in this post, is to use a single script to manage all clicks throughout the game. This is useful for a number of reasons, but mainly provides a centralized place to manage all input and to coordinate clicks according to game state. For instance, you may have a box that can only be clicked when the player character is within range, when the menu is closed, and when there is no in-game dialog happening. Placing the click logic within the box’s script in this case would require the box to have knowledge and access to the player, menu, and dialog systems, which can lead to messy and tangled code.

One more issue with handing click events inside your GameObjects is that if you want to support multiple input types, such as clicks and touches, you’ll quickly have bloated GameObject scripts that have to handle too much to do with input events, and not serving their actual purpose.

For these two reasons, I prefer a single input script that handles input events and delegates them to the objects being clicked. This way when a click and/or touch event occurs, you can simply notify the relevant GameObject that it is being interacted with - it doesn’t have to care what means of input it was, just that there was input at all.

In order to set this up simply create an empty GameObject, we’ll call it Click Manager, and attach a new script. Let’s call this script ClickManager.

Listening for Clicks

In the ClickManager script, we’ll use Update to check if the mouse has been clicked:

What we’re doing here is using Input.GetMouseButtonDown to detect if the left mouse button, represented by 0, was clicked during the current frame. This means that when you click, even if you hold the button down, this will only return true in one Update loop until the button is released and pressed again. For the right or middle mouse buttons you would use the values 1 or 2 respectively.

What was Clicked?

Now that we know a click occurred, how do we tell what was actually clicked? Since this script doesn’t belong to an actual element of our game (just an empty, non-visual GameObject), we’ll need to use a Raycast to detect what, if anything, was in the spot the user clicked.

A Raycast essentially “draws” a line between two points in the game world, and detects any physics bodies that are hit along the way. You can then use this information to determine what was hit by the Raycast and act accordingly. For another useful example of Raycasts, check out my post on Checking if a Character or Object is on the Ground using Raycasts.

For our purposes, we’ll perform a Raycast from the click location, with zero distance/direction. This means we’ll only get a positive hit from the Raycast if there is an object exactly at the click point - which is precisely what we’re looking for.

One thing to note though: the position of a click is represented by screen space, not world space. Screen space is represented in pixels where 0, 0 is the bottom left of the screen. We’ll need to convert the click position to world space in order to properly compare against the position of our GameObjects. Another minor issue is that the click position contains a z-coordinate, which is irrelevant to us in a 2D game, but will interfere with the Raycast detection since the z-coordinate does still exist in a 2D Unity game, so we’ll need to ignore that coordinate.

First up, inside the if-statement above, we’ll convert the click position to world space:

Using ScreenToWorldPoint we convert Input.mousePosition to world space which can then be used to compare against our GameObjects.

Unity raycast2d ignore object

Next we’ll perform the Raycast using Physics2D.Raycast. We’ll provide the mousePos in a Vector2 format to drop the z-coordinate, and use it as our starting point. Windows 10 version 1511 download iso. We’ll also provide Vector2.zero as the direction of the Raycast to ensure only objects located directly at the point of the click are detected: How much is scruff pro.

Unity Raycast2d

Now we can use the RaycastHit2D to determine if anything was hit by the click:

The hit.collider provides us with a Collider2D which gives us access to the Rigidbody and GameObject that we clicked on. Now we can directly manipulate what was clicked however we see fit! In the following example we simply log the name of the GameObject that was clicked, and add a force to it’s rigidbody:

For the purposes of your game, you can do just about anything with the clicked GameObject now that you know what was clicked and how to access it. Happy clicking!

Raycast Hit 2d

Full Script

Unity Raycast 2d

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