For anyone who is wondering, What was the Drawray thingy, Here it is. Debug.DrawRay(boxCollider2d.bounds.center + new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColor); Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColor); Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, boxCollider2d.bounds.extents.y + extraHeightText), Vector2.right * (boxCollider2d.bounds.extents.x * 2f), rayColor); Debug.Log(raycastHit.collider);
For anyone struggling at the 5:50 mark on getting the debug raycast to show up: Make sure IsGrounded() is called before checking for the jump key. C# implements something called "shortcutting" which means that if you have 2 AND conditions in an if statement and it fails the first one, it won't even check for the second one. If the IsGrounded() is in the second one, then it won't draw the raycast. Just something to help :)
It's necesary to make a change in the BoxCast. You need to aply a size correction for avoiding the situation when the character is next to a wall and the isGrounded function detects the Wall and let you jump again and again. Code: RaycastHit2D raycastHit = Physics2D.BoxCast(body.bounds.center, body.bounds.size - new Vector3(0.1f, 0f, 0f), 0f, Vector2.down, extraHeightTest, platformLayerMask); PD: Sorry for my english :) PD2: This video was awesome!
Your teaching style is utterly different than other people that i have seen. you are different and fully confident in your craft. hats off your confident and experience that i learn so much important things May you and your family live long !!!
Awesome tutorial. I mainly watched it to get a better grasp of Raycasts and checking for colliders and now I also know about LayerMasks, BoxCasts and Collider.bounds. Thanks :)
For those struggling to implement the first method in 3d at 2:08: if you are using a box collider like me, you can put (GetComponent().center) to get the center
You shouldn't call GetComponent() in Update/FixedUpdate etc.. you should cash the collider, use BoxCollider boxCol = getComponent() at awake or use SerializeField
Thank you! I have been stuck on this. I have been trying to use a box collider as a trigger and tell the script to check for ground that way, which didn't seem to work how I wanted it to for the game that I am making. I clicked on your video and got it done in a matter of five minutes. Also, thank you for explaining what everything did instead of just telling us to copy down some code and just trust that it works. Definitely subscribing
instead of setting all ground objects to a layer you can just set your player to the "Ignore Raycast" layer. also, for extra height, 0.01 may not work for everyone depending on your hitbox and/or collision detection method
4:17 Just some free advice, if you're going to show how to change the colour of the ray cast, don't just make the variable and assume the viewer knows what to do with it. Show the whole code, don't cut parts of it off. The code is supposed to be: Debug.DrawRay(boxCollider2d.bounds.center, Vector2.down * (boxCollider2d.bounds.extents.y + extraHeight), rayColor); but you never show the part where you add the 'rayColor' to the line, you assume we know to do that.
Everyone here who experiences a strange bug where the jump sometimes works and sometimes doesn't! This bug is caused when you run the check if the player is pressing the jump button inside the FixedUpdate() method! The checking and the main logic for the jumping has to be in the normal Update() method, the rest of the movement can stay in FixedUpdate(). The reason for this is, that FixedUpdate() (as the name suggests) runs on fixed FPS (normally 50) because thats the framerate of the unity physics loop, so when the game is running on a much higher framerate your button presses won't be recognised sometimes!
@@CodeMonkeyUnity This video was great for grasping the concept and understanding the code. I watched it several times. Both at 0.25 and 1.25 playback speed xD After some tinkering I figured out a way to make a single Raycast on the bottom side of the character work as a ground check (horizontal). Raycasts are infinitely thin and normally can't register the collider from which they originated or started inside, but for some reason it works with Physics2D, and I'm using the same approach for Wall Check Left/Right. I will probably end up with a Boxcast due to issues with slopes, unless I introduce another ray, but I'm testing it for now since I was able to write it myself. Do you have any opinions on Ray/Boxcast vs programming Collision methods? Edit: Just realized my Raycasts only worked because I wasn't using a composite collider on the Tilemap. They were always long enough to find another collider.
Nice video, mostly I work on mobile so I consider the last method to be really expensive since you are calling a getcomponent in update and also I notice that OnTriggerStay is also expensive on mobiles why I highly avoid it, so I try to do those kind of booleans in OnTriggerEnter and make them false in OnTriggerExit, so I recomend using the first and second if you are working on mobile, also call it every 3 or 5 frames to increase performance and not every update.
Hi, thanks for this video. I used to create two empty GameObject(s) under the "Player" and an "OverlapArea". It works very fine as it creates an easy setting rectangle box where I want. But, I like your method as there is no added object to the "Player" and only use a simple calculation called when needed. Thank much.
Another method is to have another game object like the third, but instead of having entire new script, we can use a reference to that object in the main script and write a function which will draw a OverlapCircleAll and it's actually pretty similar to BoxCast!!
Taught well but could've summarized previous videos as I got stuck with trying to figure out why the code wasnt working only to realise I had missed your get objects in the first few lines of code which cost me a lot of time and energy
@@Semaj0z I didn't hear him mention it in the video, but I think the reason the box collider is inferior is because it will check for collisions around the entire box. So, if a player jumps up and bumps their head on the platform above them, they would then be allowed to jump up again because the collider would be touching a platform.
Hey thanks for this man its really helpful. I'm taking an online Unity course and the instructor had us use raycasting and that didn't work at all for the game and the recast was off center and it was just a mess. I needed a different way of doing it.
@Code Monkey I don't feel like you explain why 1 method is superior to the other. I feel like the last method is actually more re-usable, as you can just add the "grounded" script to other objects, and having many box colliders is maybe a bit more work, but could be useful in some cases, like it you wanted to be able to jump from walls etc. Why do you think the boxcast is better? I picked up Unity a couple weeks ago, so I'm a total beginner tho. I'm having so much fun learning it :D
The first method only works with a single point, so if you want your character to have width you need to use BoxCast. The last method uses an extra unnecessary GameObject which has a performance cost and adds needless complexity into your game. If you're already handling character movement in one script it makes much more sense to handle grounding in there rather than access a different script in a different game object.
@@matthewtimmermans2610 So it's ok if i use collider for detect ground? i still use ray for other function that collider not so efficient, but for ground i feel like add collider will make everything easier but people said just use ray so i'm confused.
@Code Monkey There's a problem where sometimes (2-3% of the time) the BoxCast will detect a wall as ground (on the sides of theBoxCast instead of on the bottom). @Ignacio Arenas Guerra's suggestion of changing the code to this: "RaycastHit2D raycastHit = Physics2D.BoxCast(body.bounds.center, body.bounds.size - new Vector3(0.1f, 0f, 0f), 0f, Vector2.down, extraHeightTest, platformLayerMask); " doesn't help. @ReStudios' suggestion on changing the rigidbody2D to continuous (instead of discrete) doesn't do it either. I've been testing this for hours: just wall jumping (there's no ground in the testing setup), so that the only collisions happen on the sides of the BoxCast, and still there are sometimes (again, a small percentage but cannot be disregarded) where the walljump doesn't trigger because the BoxCast detected ground on the sides and therefore the jump was triggered instead.
@@CodeMonkeyUnity thanks for replying 🙏🏻 Actually, there's a second issue with a BoxCast of the exact same size as the character's BoxCollider2D, where the character doesn't detect the ground if he's standing at the very edge of a platform (so the fall animation triggers and isGrounded boolean becomes false) but the character remains on top of the platform. If I make the BoxCast a tiny smaller, I will worsen this issue, right?
I created a post explaining this issue on the Unity Forums 12 days ago. Maybe it's something with the RB2D itself, I'm not sure. In the thread, there are pictures of the RigidBody2D parameters, and also pictures of the character falling with its boxcollider and the platform's boxcollider. In case anyone would like to have a look, the post is "BoxCollider2D not falling off a platform", Jul 29.
Some help: Note that if you check if you are pressing the space bar before checking if you are in the ground the ray will only be visible when you jump.
Heh funny about that. This particular video was actually recorded all the way back in April but somehow I completely forgot to upload and last week when I was preparing to get back to regular videos I found it. There's still one more video from that time that I found as well. In the Radar Chart video which was recorded and published on Sunday you can see I'm using Unity 2019.
For argument's sake, what would be wrong with casting a horizontal ray from the bottom left of the player collider with the length of the width of the player box collider and checking using this ray? One issue that I had was it was returning true when pressed up against a wall, so I made the ray slightly smaller than the width of the player which seemed to work. I had some problems further down the road which made me reconsider how I was doing ground detection which lead me to this great video.
@@THECOLLECTOROFSOULS I actually got it working 100% (I hope) with using BoxCast! You might just want to make the box a tiny bit smaller if it's getting set to true when the player is pressed against a wall.
The third option is dangerous because it will allow you to jump when you're pressed against a wall, even if you're not grounded. You have to make the ground box smaller along the X axis, but when you do that, it causes other issues.
I was going to say OverlapBox would be more efficient, but someone beat me to it, but I have 2 more solutions not in the video: 1 - private void OnCollisionEnter2D(Collision2D collision) { isGrounded = true; } private void OnCollisionExit2D(Collision2D collision) { isGrounded = false; } 2 - isGround = footCollider.IsTouching(groundCollider);
Both are extremely fast operations, unlikely to be an issue unless you have thousands of units. I don't know specifically which one of those is faster but the benefit of the BoxCast method is you control how many times you call it, so you could just run that at most 10 times per second instead of every update.
But... Isn't there a way to get it straight from the box collider? After all, some part of the program has to already know it for the character to not fall through the ground.
You could put a script on your player that uses OnCollisionEnter() and OnCollisionExit() methods to set the isGrounded bool. Then within those methods check for a specific tag like "ground. For example within OnCollisionEnter you could do a... if(other.CompareTag("Ground")){ isGrounded = true;}
I know this might be a little unrelated to the video, but how do you check the ground material to play different sounds. For example, if a player is running on grass and then transitions to a stone road, what is the best way to check for this to change the audio when they are on different surfaces? I've read some people use raycasts, but that sounds like it could be expensive especially if there are 100s or even 1000s of players all using raycasts to check for audio. Any suggestions?
You can but don't use tags. They are string based which makes for some very nasty code since everything can easily break by just mistyping a single character.
@@CodeMonkeyUnity Still doesnt work like it does in your video, but i added a duration to the Raycast and it shows when I press space, which is good enough for me:)
Thanks for your answer. Im fairly new to programming and i havent been able to search down a solution. Maybe i just go back to boxcollider2D and drop the slopes :(
For some reason. at 7:34 when I add the platformLayerMask I can't jump anymore. Also debug.log tells me that raycastHit.collider is null while I am standing and running on a platform. Not sure where I went wrong...
@@CodeMonkeyUnity Seems to work with the second method; with the BoxCast instead of the RayCast. There must have been a typo or an incorrect value somewhere.
9:34 Question and Possible Solution: The Raycast is only projecting Directly Down (180* ) could you not "Sweep" the Raycast from side to side (as you said it casts from Point A to Point B, where Point B changes location, this should be possible as far as I know Raycasting happens per Frame (and lets say we are doing that at 60 fps), so in the space of 3 fps (Point B could change 3 times Left, Center Right, return in the opposite direction, repeat. Let me know if my Question/Solution would be easily "doable". Thanks Code Monkey and Crew
@CodeMonkey why does it trail behind the player instead of being on top if the player? sence the box colider is not trailing behind the player and is on top of it... id understand why it is not, and i dont know how i would add the velocity of the player on to it causes it to not be able to jump if i am moving towards a ledge because it is behind me when moving. i might of just missed this part in the tutorial or messed up somewhere
After doing many single raycast checks for my 3d controllers and it working perfectly, I ran into a really weird bug with double jumping: my jumps were being counted wrong, when I jumped once it was 0, and when I jumped in the air it incremented like it should. It turns out that it was immediately checking the next frame that I was still grounded, even though I should have not been. Moving the ground check to fixed or late update didn’t help at all, and it was framerate based, meaning that breakpoints would actually stop the bug from happening. I eventually tried a SphereCast instead of a raycast and that worked perfectly. Anyway, its worth making a video for 3d ground checks, because there are some weird quirks that can happen. The controller in question is a rolling sphere-style car controller
Yeah I'm having a similar issue. I don't see how using a spherecast instead of a boxcast would help? But Im glad it worked for you. I think I will try using overlapbox
Hi Code Monkey, Thanks for your video, you teach me so lot to create a game, but i have trouble when my character jump to edge of another ground, then the character detect that it's grounded. So, how to avoid this situation ? Sr for my english :)) I really hope to see your answer !
You want the "edge" to be smaller? You can scale the players hitbox to be thinner, if you make it super tiny then it will pretty much just be a single point.
@@CodeMonkeyUnity thanks for your answer, actually my problem is that when i jump near the wall (edge of another ground), the character detect that it's grounded, and it execute double jump, it flies like superman =)). So I add more code to check that it's really on the ground. The code to execute jump: rig.velocity = new Vector2(0, jumpLevel); The code to check that it's really on the ground: if (isGrounded() && rig.velocity.y == 0) I don't know whether this is the best way or not. Do you have any advice for me :D ?
He wants to keep it simple for a tutorial. While that is pretty simple it's also using some a technique that can GET pretty in depth if that makes sense, it's not the easiest thing to wrap your head around when you start out.
It does not require an extra Game Object with an extra collider. Personally I find it much better to handle all that logic through code, and if you have many NPCs/Enemies then that extra game object on all of them can be a source of performance issues.
Hey,thanks for the tutorial, but I have a problem with the third method :( My isgrounded_check doesn't get false after jumping.I'm pretty sure I did everything right and I can't found the problem. I also tried the 2 first methods and the problem was my character was unable to jump. I would appreciate it if someone helped me out! p.s:The size of my box colliders are right
For anyone who is wondering, What was the Drawray thingy, Here it is.
Debug.DrawRay(boxCollider2d.bounds.center + new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColor);
Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColor);
Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, boxCollider2d.bounds.extents.y + extraHeightText), Vector2.right * (boxCollider2d.bounds.extents.x * 2f), rayColor);
Debug.Log(raycastHit.collider);
thank you so much!!!!!!!!!!!!!!
For anyone struggling at the 5:50 mark on getting the debug raycast to show up: Make sure IsGrounded() is called before checking for the jump key. C# implements something called "shortcutting" which means that if you have 2 AND conditions in an if statement and it fails the first one, it won't even check for the second one. If the IsGrounded() is in the second one, then it won't draw the raycast. Just something to help :)
It's necesary to make a change in the BoxCast. You need to aply a size correction for avoiding the situation when the character is next to a wall and the isGrounded function detects the Wall and let you jump again and again.
Code:
RaycastHit2D raycastHit = Physics2D.BoxCast(body.bounds.center, body.bounds.size - new Vector3(0.1f, 0f, 0f), 0f, Vector2.down, extraHeightTest, platformLayerMask);
PD: Sorry for my english :)
PD2: This video was awesome!
Thank you :D
Or you can exploit this for walljumps, I guess.
you also have to add 0.1f to the y to prevent grounded when you hit the roof!
@@SMT-ks8yp You joke, but this is how many creative features in games are born -- they start as bugs.
you can also reduce the size of the collider a bit.
Your teaching style is utterly different than other people that i have seen.
you are different and fully confident in your craft. hats off your confident and experience that i learn so much important things
May you and your family live long !!!
Awesome tutorial. I mainly watched it to get a better grasp of Raycasts and checking for colliders and now I also know about LayerMasks, BoxCasts and Collider.bounds. Thanks :)
I watched so I can make my first ever game
For those struggling to implement the first method in 3d at 2:08: if you are using a box collider like me, you can put (GetComponent().center) to get the center
You shouldn't call GetComponent() in Update/FixedUpdate etc.. you should cash the collider, use BoxCollider boxCol = getComponent() at awake or use SerializeField
Thank you! I have been stuck on this. I have been trying to use a box collider as a trigger and tell the script to check for ground that way, which didn't seem to work how I wanted it to for the game that I am making. I clicked on your video and got it done in a matter of five minutes. Also, thank you for explaining what everything did instead of just telling us to copy down some code and just trust that it works. Definitely subscribing
instead of setting all ground objects to a layer you can just set your player to the "Ignore Raycast" layer. also, for extra height, 0.01 may not work for everyone depending on your hitbox and/or collision detection method
thank you monke.
Perfect! Now I can decide which method to choose and why :D Thanks a lot :D
You are a legend and deserve so much more love for sharing all your knowledge
Thanks!
4:17 Just some free advice, if you're going to show how to change the colour of the ray cast, don't just make the variable and assume the viewer knows what to do with it. Show the whole code, don't cut parts of it off.
The code is supposed to be: Debug.DrawRay(boxCollider2d.bounds.center, Vector2.down * (boxCollider2d.bounds.extents.y + extraHeight), rayColor);
but you never show the part where you add the 'rayColor' to the line, you assume we know to do that.
Hey Hugo, you are a huge support for the beginner game devs like me. Keep up the good work man! I really appreciate it :)
Thanks for the kind words! I'm glad you found the videos helpful!
good video but why is the boxcast superior to the second hitbox when they both function the same exact way?
Everyone here who experiences a strange bug where the jump sometimes works and sometimes doesn't!
This bug is caused when you run the check if the player is pressing the jump button inside the FixedUpdate() method!
The checking and the main logic for the jumping has to be in the normal Update() method, the rest of the movement can stay in FixedUpdate().
The reason for this is, that FixedUpdate() (as the name suggests) runs on fixed FPS (normally 50) because thats the framerate of the unity physics loop, so when the game is running on a much higher framerate your button presses won't be recognised sometimes!
You are the best. I stuck in this issue many months ^ ^ now it's done. Thank you so much !
Saved my project thank you so much
I loved your channel because It is easy to understand your english :)
Thanks a lot . This is the only method that worked for me. I had tried 4 different methods before and none of them worked.
Solved my problem, TYVM.
Thank you soooo much man, your tutorials are very helpful
Thanks for the explanation 👍
In the newer versions of unity you can just set the layer of your player as 'Ignore Raycast' as the fix for that bug.
Talk about superior method - I just found the superior channel ♥
I'm glad you like what you see!
@@CodeMonkeyUnity This video was great for grasping the concept and understanding the code. I watched it several times. Both at 0.25 and 1.25 playback speed xD
After some tinkering I figured out a way to make a single Raycast on the bottom side of the character work as a ground check (horizontal). Raycasts are infinitely thin and normally can't register the collider from which they originated or started inside, but for some reason it works with Physics2D, and I'm using the same approach for Wall Check Left/Right.
I will probably end up with a Boxcast due to issues with slopes, unless I introduce another ray, but I'm testing it for now since I was able to write it myself.
Do you have any opinions on Ray/Boxcast vs programming Collision methods?
Edit: Just realized my Raycasts only worked because I wasn't using a composite collider on the Tilemap. They were always long enough to find another collider.
Nice video, mostly I work on mobile so I consider the last method to be really expensive since you are calling a getcomponent in update and also I notice that OnTriggerStay is also expensive on mobiles why I highly avoid it, so I try to do those kind of booleans in OnTriggerEnter and make them false in OnTriggerExit, so I recomend using the first and second if you are working on mobile, also call it every 3 or 5 frames to increase performance and not every update.
Nice tip
How do you call it every 3-5 frames?
@@fiQmeister usually an if(Time.framecount % "desired amount of frames" == 0)
Lots of love from India BRO keep it up
Hi, thanks for this video.
I used to create two empty GameObject(s) under the "Player" and an "OverlapArea". It works very fine as it creates an easy setting rectangle box where I want.
But, I like your method as there is no added object to the "Player" and only use a simple calculation called when needed.
Thank much.
Even in OnTriggerExit2D we should check if the collider that is exited is the ground collider
Thanks, very helpful!
always find you when I'm looking for The Best Code, Thank You🌹.
saved me thanks !!!
Another method is to have another game object like the third, but instead of having entire new script, we can use a reference to that object in the main script and write a function which will draw a OverlapCircleAll and it's actually pretty similar to BoxCast!!
Taught well but could've summarized previous videos as I got stuck with trying to figure out why the code wasnt working only to realise I had missed your get objects in the first few lines of code which cost me a lot of time and energy
4th method : add 2 raycasts in x axis from the bottom of the player with new Vector3(boxCollider2d.bounds.extends.x,0,0)
i believe there is easier ways to do the 3rd one but maybe the way i use is not the best, still good video, i learn more than what i was looking for.
O dont get why BoxCast is the best option over a collider. What is the advances and disadvantages of those alternatives?
Thanks, great video 😁
The boxcast checks the entire ground underneath the player. As demonstrated in the video, only this will allow jumping on slopes.
@@ShenDoodles so does the box collider
@@Semaj0z I didn't hear him mention it in the video, but I think the reason the box collider is inferior is because it will check for collisions around the entire box. So, if a player jumps up and bumps their head on the platform above them, they would then be allowed to jump up again because the collider would be touching a platform.
@@ShenDoodles it's not the only way :P
Good video explaining the basics. Building out a full controller using raycasts/boxcasts is a lot of work.
Simple and concise, thank you!
Hey thanks for this man its really helpful. I'm taking an online Unity course and the instructor had us use raycasting and that didn't work at all for the game and the recast was off center and it was just a mess. I needed a different way of doing it.
Great tutorial, Thanks
Thank you!
Concise. Great explanation. Good tutorial. Thank You.
@Code Monkey I don't feel like you explain why 1 method is superior to the other. I feel like the last method is actually more re-usable, as you can just add the "grounded" script to other objects, and having many box colliders is maybe a bit more work, but could be useful in some cases, like it you wanted to be able to jump from walls etc. Why do you think the boxcast is better? I picked up Unity a couple weeks ago, so I'm a total beginner tho. I'm having so much fun learning it :D
The first method only works with a single point, so if you want your character to have width you need to use BoxCast.
The last method uses an extra unnecessary GameObject which has a performance cost and adds needless complexity into your game. If you're already handling character movement in one script it makes much more sense to handle grounding in there rather than access a different script in a different game object.
one is not superior, they are all situational.
@@matthewtimmermans2610 So it's ok if i use collider for detect ground?
i still use ray for other function that collider not so efficient, but for ground i feel like add collider will make everything easier but people said just use ray so i'm confused.
@@Luca-nq4gy There's nothing wrong with using a trigger collider. Just use what works best for you.
Oh, thank you man!!!
Hey CM awesome video, But we can also use the player collider for the ground check then why to use a raycast ?
@Code Monkey There's a problem where sometimes (2-3% of the time) the BoxCast will detect a wall as ground (on the sides of theBoxCast instead of on the bottom). @Ignacio Arenas Guerra's suggestion of changing the code to this:
"RaycastHit2D raycastHit = Physics2D.BoxCast(body.bounds.center, body.bounds.size - new Vector3(0.1f, 0f, 0f), 0f, Vector2.down, extraHeightTest, platformLayerMask); "
doesn't help.
@ReStudios' suggestion on changing the rigidbody2D to continuous (instead of discrete) doesn't do it either.
I've been testing this for hours: just wall jumping (there's no ground in the testing setup), so that the only collisions happen on the sides of the BoxCast, and still there are sometimes (again, a small percentage but cannot be disregarded) where the walljump doesn't trigger because the BoxCast detected ground on the sides and therefore the jump was triggered instead.
Just make the BoxCast a tiny bit smaller than the physical collider
@@CodeMonkeyUnity thanks for replying 🙏🏻
Actually, there's a second issue with a BoxCast of the exact same size as the character's BoxCollider2D, where the character doesn't detect the ground if he's standing at the very edge of a platform (so the fall animation triggers and isGrounded boolean becomes false) but the character remains on top of the platform. If I make the BoxCast a tiny smaller, I will worsen this issue, right?
I created a post explaining this issue on the Unity Forums 12 days ago. Maybe it's something with the RB2D itself, I'm not sure. In the thread, there are pictures of the RigidBody2D parameters, and also pictures of the character falling with its boxcollider and the platform's boxcollider. In case anyone would like to have a look, the post is "BoxCollider2D not falling off a platform", Jul 29.
Thanks a lot
this was really helpful
What do you think about use to Physics2D.OverlapCircle()?
Some help:
Note that if you check if you are pressing the space bar before checking if you are in the ground the ray will only be visible when you jump.
Wow ! somehing great today
Good explanation Perfect work
Nice tips, thank you.
Just curious if there's a reason you haven't updated your Unity to 2019?
Heh funny about that. This particular video was actually recorded all the way back in April but somehow I completely forgot to upload and last week when I was preparing to get back to regular videos I found it. There's still one more video from that time that I found as well.
In the Radar Chart video which was recorded and published on Sunday you can see I'm using Unity 2019.
Dat thing is one that always needed and always forgotten by me. Thanks!:)
For argument's sake, what would be wrong with casting a horizontal ray from the bottom left of the player collider with the length of the width of the player box collider and checking using this ray? One issue that I had was it was returning true when pressed up against a wall, so I made the ray slightly smaller than the width of the player which seemed to work. I had some problems further down the road which made me reconsider how I was doing ground detection which lead me to this great video.
I have this exact same issue using boxcast, still looking for a solution.
@@THECOLLECTOROFSOULS I actually got it working 100% (I hope) with using BoxCast! You might just want to make the box a tiny bit smaller if it's getting set to true when the player is pressed against a wall.
9:36 Recommended Method
by whom?
@@allwoundup3574 what do you mean?
@@jamado9067 By whom is that method recommended?
@@allwoundup3574 code monkey says it is the superior method (12:05)
Thanks!
3rd one is awesome
But understanding raycast may help in developing shooter games
Thanks man, you're always such a huge help
The third option is dangerous because it will allow you to jump when you're pressed against a wall, even if you're not grounded. You have to make the ground box smaller along the X axis, but when you do that, it causes other issues.
This also happens with the second one.
I was going to say OverlapBox would be more efficient, but someone beat me to it, but I have 2 more solutions not in the video:
1 - private void OnCollisionEnter2D(Collision2D collision)
{
isGrounded = true;
}
private void OnCollisionExit2D(Collision2D collision)
{
isGrounded = false;
}
2 - isGround = footCollider.IsTouching(groundCollider);
You're a hero.
This helped a lot. What do you do in a case where you bump into a floating platform and touches platforms from the side?
Thanks a lot!!
thanks man you are awesome!!!!
really helpful thanks
What about computational effort for the different methods?
Is a Boxcast more demanding than a simple collider for ground detection?
Both are extremely fast operations, unlikely to be an issue unless you have thousands of units. I don't know specifically which one of those is faster but the benefit of the BoxCast method is you control how many times you call it, so you could just run that at most 10 times per second instead of every update.
@@CodeMonkeyUnity Maybe you can do a profiler Tutorial about this? ;)
It doesnt let me write bounds after boxCollider2d (1st method) why?
it says that object doesn't contain a definition for bounds
maybe your getting the component incorrectly, or you're getting the wrong component
you should declare it and GetComponent it in the Awake function
But...
Isn't there a way to get it straight from the box collider?
After all, some part of the program has to already know it for the character to not fall through the ground.
You could put a script on your player that uses OnCollisionEnter() and OnCollisionExit() methods to set the isGrounded bool. Then within those methods check for a specific tag like "ground. For example within OnCollisionEnter you could do a... if(other.CompareTag("Ground")){ isGrounded = true;}
there is collider.IsTouching(otherCollider);
thank you
For some reason my RayCast is pointing to another direction?
Loved this video, it helped me a lot. Thank you very much!
great video
I know this might be a little unrelated to the video, but how do you check the ground material to play different sounds. For example, if a player is running on grass and then transitions to a stone road, what is the best way to check for this to change the audio when they are on different surfaces? I've read some people use raycasts, but that sounds like it could be expensive especially if there are 100s or even 1000s of players all using raycasts to check for audio. Any suggestions?
Yeah, Thanks so much
Uh... the raycast Color isn't working, just gives me a white color.
The groundcheck worked though so it's fine, thanks!
nice video!!!! but is it ok to use tages insted of layermasks?
You can but don't use tags. They are string based which makes for some very nasty code since everything can easily break by just mistyping a single character.
@@CodeMonkeyUnity i agree thank u so mush
Thank you, such a good video, but i have 1 problem, I cant see my arrow from the Raycast?
Make sure you have Gizmos enabled in your game view
@@CodeMonkeyUnity Still doesnt work like it does in your video, but i added a duration to the Raycast and it shows when I press space, which is good enough for me:)
thanks
Cool instruction!!!
Hi. Nice video. Is there a way to make the boxcast a little smaller in with, since i use capsuleCollider2D.
Sure, you can define whatever size you want
Thanks for your answer. Im fairly new to programming and i havent been able to search down a solution. Maybe i just go back to boxcollider2D and drop the slopes :(
you saved my life, thank you very much
For some reason. at 7:34 when I add the platformLayerMask I can't jump anymore. Also debug.log tells me that raycastHit.collider is null while I am standing and running on a platform. Not sure where I went wrong...
Is the platform game object with the collider on the same layer as the one you chose in the layermask?
@@CodeMonkeyUnity Yeah I just double checked. Does the layer the player is on make any difference? (it's on the default layer)
@@CodeMonkeyUnity Seems to work with the second method; with the BoxCast instead of the RayCast. There must have been a typo or an incorrect value somewhere.
thanks for unlocking my mind bro
9:34 Question and Possible Solution: The Raycast is only projecting Directly Down (180* ) could you not "Sweep" the Raycast from side to side (as you said it casts from Point A to Point B, where Point B changes location, this should be possible as far as I know Raycasting happens per Frame (and lets say we are doing that at 60 fps), so in the space of 3 fps (Point B could change 3 times Left, Center Right, return in the opposite direction, repeat. Let me know if my Question/Solution would be easily "doable". Thanks Code Monkey and Crew
Sure that would be doable but would be inconsistent and needlessly complex compared to just doing a simple BoxCast.
@CodeMonkey why does it trail behind the player instead of being on top if the player? sence the box colider is not trailing behind the player and is on top of it... id understand why it is not, and i dont know how i would add the velocity of the player on to it causes it to not be able to jump if i am moving towards a ledge because it is behind me when moving. i might of just missed this part in the tutorial or messed up somewhere
After doing many single raycast checks for my 3d controllers and it working perfectly, I ran into a really weird bug with double jumping: my jumps were being counted wrong, when I jumped once it was 0, and when I jumped in the air it incremented like it should. It turns out that it was immediately checking the next frame that I was still grounded, even though I should have not been. Moving the ground check to fixed or late update didn’t help at all, and it was framerate based, meaning that breakpoints would actually stop the bug from happening. I eventually tried a SphereCast instead of a raycast and that worked perfectly. Anyway, its worth making a video for 3d ground checks, because there are some weird quirks that can happen. The controller in question is a rolling sphere-style car controller
Yeah I'm having a similar issue. I don't see how using a spherecast instead of a boxcast would help? But Im glad it worked for you. I think I will try using overlapbox
@@raswaking8172 Frankly I don't know why it worked either, maybe since the sphere only had one spot on it that was 'lowest" to the ground?
Why not just use the box collider that is already attached to the player?
Because it could collide with walls, and ceilings too. You just want to check if the character is colliding with the ground.
Perfect class
damn he really called me out on the last one 😂
Hi Code Monkey, Thanks for your video, you teach me so lot to create a game, but i have trouble when my character jump to edge of another ground, then the character detect that it's grounded. So, how to avoid this situation ?
Sr for my english :)) I really hope to see your answer !
You want the "edge" to be smaller? You can scale the players hitbox to be thinner, if you make it super tiny then it will pretty much just be a single point.
@@CodeMonkeyUnity thanks for your answer, actually my problem is that when i jump near the wall (edge of another ground), the character detect that it's grounded, and it execute double jump, it flies like superman =)). So I add more code to check that it's really on the ground.
The code to execute jump: rig.velocity = new Vector2(0, jumpLevel);
The code to check that it's really on the ground: if (isGrounded() && rig.velocity.y == 0)
I don't know whether this is the best way or not. Do you have any advice for me :D ?
You can also do this for the debug colors, bro. :)
Color rayColor = collider ? Color.red : Color.green;
It's the same.
He wants to keep it simple for a tutorial. While that is pretty simple it's also using some a technique that can GET pretty in depth if that makes sense, it's not the easiest thing to wrap your head around when you start out.
Yeah, makes sense. 😁
wait, so why is the boxcast method superior to the last (beginner) method you described?
it passes both the slope and edge case.
It does not require an extra Game Object with an extra collider. Personally I find it much better to handle all that logic through code, and if you have many NPCs/Enemies then that extra game object on all of them can be a source of performance issues.
why castbox is better then second collider ?
love you :>
I had used isGround in Update and Physics2D.BoxCast is jerked when i use transform.position for movement of gameobject. Help me, pls !!!
One question to the box cast, can I detect on what site the boxray collided with something or just that it collided at all?
how do I make sure my jump animation is active when the groundcheck is not interacting with the platform layer? I am going with the 3rd option.
Add a boolean parameter to your Animator and set it to the same as your isGrounded bool.
Is there a way to make this with capsule cast or something similar for 3D
How about Physics2D.IsTouching
3:15 I just realized he made a funny typo: he typed extraHeightText instead of extraHeightTest.
Hey,thanks for the tutorial, but I have a problem with the third method :(
My isgrounded_check doesn't get false after jumping.I'm pretty sure I did everything right and I can't found the problem.
I also tried the 2 first methods and the problem was my character was unable to jump.
I would appreciate it if someone helped me out!
p.s:The size of my box colliders are right
for he first method, if the project is in 3d, what should I use, instead of physics 2d?
Use Physics