Raycasting in Unity | SandS Arts | Skillshare

Raycasting in Unity

SandS Arts, Game developer

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
8 Lessons (49m)
    • 1. Intro

    • 2. Basics with presentations

    • 3. Ray in 3D

    • 4. Layer mask and hit information

    • 5. Ray in 2D

    • 6. Enemy escape AI

    • 7. Ray from camera

    • 8. Single jump mechanic


About This Class

In this class you will learn "raycasting" in Unity from basics , examples with presentations are also provided for better understanding of the concept , extra examples shall also be added if asked.

Examples include -
1.Creating a simple ray in 3D
2.Creating a simple ray in 2D
3.Creating a ray from camera to mouse point which is a part of code in click to move mechanic as in DOTA 
4.Creating an enemy escape AI by using raycasting.
5.Better understanding of layer mask and hit information in raycasting.
6.Coding mechanic of single jumps in 2D games.

" !!! Extra examples shall be added if asked !!! "

Click to join our discord server

Music used in all the videos are by Argofox.


1. Intro: Hey, give Villa boasts Sankyo from San Sucks. In this class, you learn about recasting. First, we'll see what is recasting why we need to use it in gains with some examples. Examples include creating a simple rate from spiders head in its forward direction with the deck collusion doing the same in two D programming. Simple Enemy escape. AI. Using recasting, - creating every from the camera to the mouth. Position to destroy some objects with Collide with the three creating a great with the collision with the ground on if the player is rounder will enable him to jump. We have to do this toe, allowing multiple times when players in the air we learn about the different number of arguments that recasts function. Pigs that include Liam asked on the hit information with which that really has collided with If you need some more examples, just say in my discourse over are in the class discussion spinal. I tried to include it on 40 2. Basics with presentations: in this video, we'll take a look at what is recasting. Why is it used in gains on some examples? So what's Ray passing? In the process of creating an invisible line with custom length, on which point in some direct it is like a line with other that born. I'm an important but as a constant stop start point some direction on someone. In this case, direction is right down on length is one meter. As in real world, we cannot see the air medium in game. Bulls player cannot see the race. Yes, it's invisible. However, if you want to enable the player to see the real, you can use line. Gender component in unity White recast. It's used to create an invisible line. Let's layer cannot see while playing to detect collisions when those some objects, for example, in games like Dota two, when we kick on the terrain or on the ground, the player moves towards it so that mechanic is a team through recasting to perform some actions. When some of that hits the invisible living. For example, in our game, if you want a player to jump once, we will have to use recast it. Well, I'll explain it in the next life. Do you object? I, for example, if you have any one which suit any? Me, too. When anyone who is in sight our Renate delights with the invisible rays off enemy one recasting should be you. I'll explain this to, after the next life on many more example. What, and I'll get if you want the players to jump only once before enabling the player to jump will help. It took. Rather, the player is standing on the ground. Here is the zombies. The player to check, whether it is colliding with the ground, will have to pass theory or quit on invisible life. We'll have to create the real from the foot off the player, which can be awful. And one millimeter here, As you can see, the rate is colliding with the ground so well that is grounded variable. True on, based on this condition, will enable the player to It is around that, he said. The truth Will anybody need to jump? Uh, as we are already. Anybody that clear? John, the playoff is in here now. As you can see, the way is not colliding with the ground, and with that he drowned. That falls. And if he's grounded, a set of balls will not enable the player to jump. As it is said before, you wanted the player press the junkie. Let's say it's the space button near and not be able to. You can only be able to jump when he's grounded. A separate group and it is only set it through. When does the next police with the ground? Example. Two. In R V. If we have one enemy in this case, it's for about on. If we wanted to to at another enemy off other kinds. Here it's a zombie. We'll have to use recast will cast a tree or create an invisible line from Cleo's head. Britain's offline See one meter. This is the piece where we are ice for objects as it can perform some actions when it did. Exclusions with the race casted are created as this reef is not lighting with any other objects, it will be set to fall. It is just a variable here as soon as it detects the enemy off other kind. As this really is colliding with the enemy, too, it will be set the proof on the fifth Day, said, True, we'll call a function called Shoot so that player will be able to shoot at the enemy off other kinds on. When the bullet hits, the other kind of enemy big Dies. This is all about recasting. 3. Ray in 3D: Hey, game the both the Shankill from sand stocks in this video picture, a simple agree that the text collisions in this scene I have just a few models. Yes, I tried the link for this model in the class description, and also you can download the project files as you can save time by not dragging all the models into a seat. If I just played rat moves towards the spider certain distance I'm stopped as rack containing stripped called Move, which translates it for most in the forward direction the rat my deployed with After some time the script destroyed herself with stop director moving now credibly from spider heads in the forward direction. So let's where the MP came object really limit to that point, I grabbed it to you more so that it would be friend of the heads. Yeah, this is way can also create every from this point. But you created a new 0.0.5 that because it is actually from this point, there's a chance that the re collects with the spider itself on the X collision. That's why we created another point out off, despite a body so that it did X collisions with other objects except this spider. However, you can also create the read from this point on, ignore the collision with the spider. Its search for that we have to use Lamma. I'll discuss about lame ass later, but now we are creating a real from the phone. Let's read a script called Spider Cast Finale to Spiders Game objects as we need to create every from this point with the reference off the dog. So occurred a public public because I want to see the variables Inspector on the variable can. Also the access in Other scripts are in other classes. Now we want to get the transform off this object as we want to get the position. Therefore, as a public transform. I'll call it that point. No, enough metal. If you want to create a re in treaty, we need to sit for six, not recap. Rick Up Stand big number of Parliament. The Force one is three. The 2nd 1 is great with some distance. This will be discussed later. Now we want to focus on the set up of the first argument that we want to pass the origins, which is the point the directions should be repertory forward as we want to create a race in the forward direction, Start point is a transformed transformed. We only need to ask the position off the transform their when it just be that point that position. Next, we need to pass directly as we want to create a day in the follow direction off the spider we need to see transform Forward, Transformed up for both has a magnet field. So as he wanted way off magnitude greater than once, we can fast the lengths off theory as the third argument. For that, we create a public float variables, unpacked it out, argument well in the three on the land and get sleep. Yes, you'll not be able to feed the race because it's an invisible line, as if you want to be that way. Must stay dark logs place method In the country, people got. Drori creates a way in, seen as last in the game. You, if we enable give, also feed in the game view between Able give more but clear cannot see while playing Nadine For that we have to use lines under competent well, this about it later, even duct Rodri fix a start buying. So for in good position, the next argument is the direction. So it transformed the forward as we needed raid the power direction off this fighter from the problem. As I said, magnitude off this transform before we're is one. People that drop. Do not take 1/3 argument with his office flow data type or it does not take the length off the three. Therefore, three multiply length to transform goes forward magnitude off. This will be off then. Therefore we'll get every which is off you. You can also specify the color off. Three I think color dot Now, if now we cannot see that if you want to see the way we need to enable this gives most confident in the theme view. If we want to see it in the scene, way have to enable it in the game view. If we want to see it in the games, remember, cannot see this race in the games. Nothing happened because we have not recorded anything that will be done something Polites with. So if you just answered this inside the condition, the things inside this block will be executed. If something polite with the street. So it's something polite with three this place in the country. So I got log. Let's go back to the object must also contain colliders. Therefore, we like a box collider competent. I said the size off this 233 and three I said the size too. Three four on by now with his place collisions from the rat should really practice on The message will be displayed Yes. Let me finish this place. You can also see over here the's detective collisions on it printed these messages. Things inside the city block will be executed as long as something collides with on right this colliding with it currently that things that is the message will be displaying continuously. So by this evil magic place you can see that are increasing continuously. So we created a simple by using metal time For what 4. Layer mask and hit information: in this video, we'll use Liam Asked to know collisions with the clear. Are we the object from which you create the re? That's at a new script to the spider? I'll call it Spider Cast, too. In this clip, I'll just create a public road variable Corlin on copy. The Seem cold available. Inspire a cast strip. I'll explain this in the first video. Beast it here instead of start. For in your position, I transform the position even here is transformed or for the she. This recast also takes an extra argument. Pretties dilemma. What is Lamma? You can see something called jail or here by different. Every object layer will be set to deport. It is just like name often. Object. If you understand she ate this object to the objects name. Something called clone will be others, so the name of the object will not remain the same when you spawn the objects. So reuse tax to perform some actions like finding all the enemies in the sea when they came off. Find game object with Tex enemy After adding a bad to the enemy and setting that that as any in the same way we can add Leo Aaliyah called Player. Go back to fight, Ato said the Lear toe player and only city to this object. Now only this object has a layer called player remaining ballistics As default, Leo now occurred of Public The Emma. I'll call it a player Leo on fast near Leo as the last argument for war distance, the way that we have created only collides with the optics with has earlier saying that up the Leo as I'm here, if the Leo clear, this ray only collides with the player, but we want the race to collide only with the enemy. So we'll just go our layer on reading this to any. So now we're setting people on set rat layer enemy. Now this race only collides with rat object as it has a near of course, enemy will display The message called Hit on but also destroyed will destroy the right game object. Now we want to get the object to which this really has collided. For that, we need to create a label called Recast It. I'll call it Hit on here. I'll say about it. What? This does it. Something collides with the ray that information will be returned. So this hit variable. I'm sending the information. So this hit radio. But so as it is, the information off the collided objects we need to use recast it as the day that I feel as a hit, as I want to destroy the object to which this Riaz collided at the hit that transformed the game. Object will get back to unity, said the lead to three. Obviously now, as soon as the radicalized with Ray gets destroyed. But it's not. Why is it so? Because it be enabled? Gives much. We can see that the rays created the left direction with reference to the fire because for our direction, according Toa, this game object is this direction. So blue access. It's forward, but we want to pass a red. The rest in this direction as it is red color. We want to say class form that right now is rat liver destroyed as soon as it hits the three. Yeah, it did also the message business, please. This was a worldly in my 5. Ray in 2D: in this video will show a simple ray that the text collision in this thing I have just a few more years. I'll try the links for this model in the class descriptions, and also you can download the product piles as you can save time by not dragging all the models into the seas. If I just hit slaves. Barack most towards the spider to certain distance stops as rack containing strip called Move, which translated or moving in the forward direction off the rat. My deploying with After some time, the script destroys itself. Which stuff? The raft removing. Now we'll create every from spider heads in the forward direction. So let's greater MPP market. We limit to that point I drag you here on so that it will be in a friend of the head. Yeah, this is fine within. Also create every from this point. But we created a new point wives at it because if you cast a read from this point, there's a chance that the rig collide despite itself on the X collisions. That's why we created another point out off this fighter body so that if the text collisions with other objects except this spider. However, you can also create the rates at this point and ignore the collision with the spider itself . For that, we had to use Lamma. I'll discuss about Amos later, but now we are creating a re. From this point, let's create a stripped called Spider cast Inarritu fighter game of as we need to create every from this point with the reference off the object. So we create a public public because I want to see the variable in inspector on the label can also the access in. Other scripts are another class is now. We want to get the transform off this object as we want to get the position. Therefore, as the public transform, I'll call it that point now in update measures. If we want to create a ring in treaty, we need to step physics. Don't recast Rick up. Big listen. Number of arguments. The 1st 1 is three. The 2nd 1 is free with some distance when this story will be hit. Spoke when discuss these things later. Now we want to focus on this set off in the first argument that we want a part is the origin, which is the point. The directions should be record three daughters forward. As we want to create a break in the forward direction, start point is off transformed. One consist of position, rotation and scale. We only need to act in the position off the transform. Therefore, when it to stay that point, that position next really passed the direction as we want to create a day in the forward direction off the fighter. Really to see transform dot forward Ben transformed Forward has a magnitude one. So as we wanted three off magnitude greater than one we can pass the length off. Dearie has deterred arguments for that. For the public float variable for length on a positive disorder. Arguments. We'll enter. Three. Dylan. Yes, you will not be able to see the race because it's an invisible line as that. If you want to see the way we must say debug dark, log this place be method. In the concert, Dr Drori creates a race in the steam has left in the game. You, if we enable gives more, but also in the game you enable gives most but clear cannot be while playing the game that we have to use line vendor confident we'll discuss about it later. People Ducks, Roddy fix a start going. So start boring Dodge position. The next argument is the direction, so it's transformed the forward as we needed. Rain the forward direction off the spider plant from the trouble I said magnitude off the transform. The clover is one people don't drop. Do not take 1/3 argument flow data type or it does not take the lens off the way. Therefore, three multiply length to transform got forward magnitude off. This will be off then, therefore will get a raise, which is a bad dude length. We can also specify the color off this ray. I'll take color dot now. Now if we we cannot see the if you want to see the really enables. This is most competent in the scene view. If you want to see it in the scene, we have to enable it in the game view. If you want to see it in the game, remember, Player cannot see this race in the game has clearly now. Nothing happened because we have not quoted anything that will be done. Something collides with. So if we just enclose this inside the condition The pink inside this block will be executed if something collides with this. So it's something collides with the race as this play message in the country. So they got log. Let's go back to the object must also contain a collider. Therefore box collider confidence. I said the size off this 233 and three I said the size too. Three four on five now hit Lee Collision from the rats should be directed on the message should be displayed. Yes, you can also speed over here. These rays detected collisions and it printed these messages. Things inside the city block will be executed as long as something alights with it As I write this colliding with it, please. The things that is the message will be this thing continuously. So by disabled now as my plate, you can see that messages are increasing continuously. So we created a movie by using Dr Rigas Mecca 6. Enemy escape AI: in this video, we'll create four race so that this object will escape from the player on a world collision . Will will create array in the airport, directions in the right direction, downwards on, then left direction. So will our steptoe. This We'll call it escape. Now. You can create four points. Take the reference off that and you those points. Otherwise, we can use the pollution off this object on ignore collision by using lay a month. So I mourn with a layer mask, picnic a lot a new deal. Call it clear on select Octopus said. It's layers to place. Really Box collider touring to the clear. If you don't add this box collider, you can create the race from this object position without using Lamar as it does not get a collision with this object itself. So as I'm using layer mask on, I need a box collider. So now I'll just a boxful either, too, because in some games, enemy strict Wild Books collider land on the platform are on the ground and interact with the player. Let's go back to this place. I'll take a reference off the Neymar. I'll call it Leo on the update metal as the basic story, not recast from the current position in the upward direction. I'll create a public variable off load, I'll call it, and I'll pass it as the third argument. Alan, close this line inside because I want to perform some action. If some collision is directors were busy. I thought this 54 times because we need to create four. I need to create a real in the right direction in the downward direction we can't transform got down because transform does not contain it. So we'll just add a negative sign toe transformed up because transformed down or the dollar direction is opposite to the upper direction. Transforms also does not contain a definition for left, so we'll are negative sign to transform that right. So here we just created four, If therefore directions right down on in the left direction. If you want to see it, we want to use people. Don't drive a and I'll include those Sarah Good in a separate functions core drop here. I'll say people start drawing on past transformed the coalition as the first argument form up as second my supplied with on the color will be green. I'll copy the steam lines based it three more times A lot of negative sign. 40 downward direction. That's right on the negative sign transformed right, You re created bore line. Now we'll call that function in the update metal. If you just get back to unity, I select the deal. The land and it leaves. We can be the four week Here they are. Al. Increase the land 23 No. This re created in our four directions for light with the player I need to move the enemy in the downward direction. So what I love is they transform the translate with just translate or moved is object in the direction. Specify? I want to board in the downward direction. Therefore, I made a sign to transform. Got up that sex and from daughter has a magnet. You off one therefore a new valuable offload data type. I'll call it, move on and multiply the most also with times don't attack. It allows us to move objects, not by plane. If we more objects by name, the object may move too fast or too slow, depending on the wise hardware and simple words we want to morning object in the same speed on all the devices. Introspective off. It's hard now. The place colliding with Rick. I went in the right direction way have more the enemy in the left direction. So we'll copy the steam line off court. Let the negative sign beyond they transformed, not write. Copy this two more times. It plays colliding with the bottom. Do we have to move in? They transformed daughter, the place colliding with the left we have, the more the enemy in the right direction. Therefore, transform. Not right. The service and head back Islander. The movie has fired. Now, too great a symbol. Stripped by this, we can control the mayor or the Octopus. I'll call it player control. There are multiple ways to court declared controller. Now I'll be altering the velocity to control it. A player In order to alter the velocity, I had a rigid body component on Don't the gravity field with little because we don't want a player to fall down as there's no ground over here. Fill up on the play. Control a script as well be altering the velocity we need toe. Get the reference off this rigid body so you can say public reading body truly on drag and drop the same object. So that a lot Pollard, we can say rigid body to be alcoholics are be on in a start functions as the R B was get competent rigid body. So what happened to you whenever we hit the play button are when the player starts again? The rated body attached to this glowing object R b no in the fixed update metal way have to do it in the fixed up method because physics, things up performances, the treatment still, as they are, be dark velocity. People knew rectitude and I'd be passing input. Get access, Korean. So this court just gets the horizontal inputs from the player. If you just go to edit sittings, you can see something going input over here and under that you can see access. And here you can see something called horizontal. So we had about the same strength. Well, here it will get the horizontal input which are left right are a the then who is the input ? Don't get axis radical. This vertical is available here, so those are up down our s and w key. The man human value that this return is one. So if you want to move the player fast or with certain, we need to multiply it with the most. Therefore regret. A public label will call it Moves on Multiplies is with mostly anyone here. Move rewarded lineup. Would it just be slaves? Velocity are rigid body velocity based on the players. Input in court. The grassy horizontal visit one current player president Positive buttons with these right are positive alternate body The player press the rightly residence one it mostly to one in tow too. So this will be to different. Video is no vertical buttons are pressed so here to form a zero present, which means we are playing velocity in the X direction, which is to playing no velocity in the Y direction. This will be easy with the same with vertical. Also, if he plays the positive button up our WC this is the one on it is my reply with Morsi so the player will be morning in the Y direction. If we are pressing board the peace, both will weaken one star positive button. David Ricken minus one. Your nephew button addressing the negative buttons. What is left. Are you taking in case of horizontal down Whoriskey in vertical It written minus one clear Will move along the negative X axis on here. London, AP Wire. If we're pressing both the beef will be Alan Velocity in the X direction as well as in the Y Direction will stay. This get back community will enter the move without one. I go toe so at a business scene, right? The the script. No, the political life would be and anymore, Picholine. And I mean in the right direction. Seeing happened aboard, hungry on the right for work. 7. Ray from camera: if this would you will Gregory from the camera through the mouse position. Like the games in Daughter, this mechanic is use if I just play on airplanes more left to right. As you can see, it just has the most script attached to it, which I had explained in the first video. Now let's select the camera descriptor. We'll call it camera cast now in the update with Great and Me. I'll call it three, which is equal to camera. Got me? Don't clean point to which extent dot mouth position as you organize for us. I'm creating every position. Our origin is the camera camera doctor. Just get the main camera in the hierarchy. It just seems as doing game object dot Fine game object with stag main camera as the main camera hasn't a cold Mein Kampf camera don't mean this does the same job. Instead of typing this thing, we can type camera that I am passing input that mouth position as the argument The whole line means I'm creating agree with camera as its start point on the most born as its informed, Let's create a battery now if I just say debug dot strongly Now we have to pass. Born on the direction that foreign will be read or origin on the direction will be re diving. I might reply 100 on. The color will be blue on my blanket with hundreds dusting with the land up. Really Now if I on any little gizmo, I can't see them against you But if I pause the game more because they're here, you can see it. Indy seen Now reach up if the recall lights with something. So for that, we should see physics Doctor recast. I'll pass three on the distance argument it says 100 on. Depict collides with something I'll destroy it Now I need the object with this wreck Allies Therefore, I need to create Ray Castaic variable So I traded here. I'll call it it on here. I'll say out it So what this does after creating? Really? If it detects collision with the object, will just Britain that information. So this hits variable which will be off request hit data guy So that great collects with this plane. That information will be fast that Hey, a plane has collided with the three, so I guessed right that game on deck by saying The transform game off Go back to unity Article. Idol could've plane box Collider, Politis toe all this objects on the plane I got a box for life. I just disabled. I should only destroy your object if it collides with something. And if I see most button input, get mouse button down little because it is the left mouse button and head back to unity. Now aim at the airplane on his left mouse button disappears. Even the objects on this plane disappears. If I just pause again, you can see the way in the scene. You The mountain will not disappear because I have not added the collider to this mountain . And also you can see the degree here is not reaching the mountains because it's lent it 100 . If you increase it, the baby will be able to reach the mountain as well. Oh, it disappeared the plane as well. Accosted radical idea If you don't want to disappear, are destroyed a plane You could near my as an argument here recognize the collusion with the plane. Thanks for watching 8. Single jump mechanic: in this video, we'll create a way from the foot off the clear in the downward direction and enable the player to jump the face colliding with the ground. So it really intriguing object on position it here, I'll call it put. You can also create the re from the clear position in the downward direction on use a layer mask to ignore collision with the players here. I'll just creating every from this point now let's Allah box collider to re component Already I moved a good point. I have out of the collider to the background so that player will be able to collide with it . Let's our script will call it Jump Controller will make the players jump by force to the rigid body, so we have to add a rigid body to component. Now we need the reference off this rigid body. So it's an visit. 40 duty. I'll call it RB and then the stock. My RV. It was good confidence. Rigid body, too. I have explained what this dust in the previous really fix up the mess R B don't are fools , so we have our ports in the upper direction. Therefore will say two dots up will multiply it wit source, which is a variable that will be reading now. As I have said, director Kudat Up has a manager of one. We want to provide force off manager more than one. We have to multiply it with force. We only have to enable the Plato jumps if he's colliding with the ground. Therefore, to set collisions meaning since physics to re dock. Recast. Let's take a reference off the start point. But if you we wondered a in the downward direction so it's oppose it. Toe transformed up on Let the length be 0.1 really enclosed this inside it. So it's 0.1 because it's a look value. So here we are, adding pulls to the rigid body, confident the re is colliding with something. If you wanted to collide only with the ground, just take a reference off the name A and then parted here. I'm not using any other or six down the ground. I'm not being building The layer mask will enable The player could jump on the the player press this place button they get down. I will return true if we press this base but so definitely a press. The button check whether the player is grounded. Our talk whether the players colliding with the ground I'm tired, maintains this to one because point oneness too small. Let's get back to unity on Set the course to 1 50 honest drag and drop the present hits late. Now let's also locked rotation off the body. Now I speak button. Blair jumps. If I try to hit the space buttons when player is in the air, still not be able to some because after passing the bellybutton you're talking, is the players colliding with the ground? Only where are in the food. We just remove this line off court. There will be able to jump. You wanna say it in the air, as you can see now I'm pressing the space button multiple times. Soto Award. This We have the truck. If a player is colliding with crowds, then only enable the player to jump