Field of View Effect in Unity (Line of Sight, View Cone)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to make a very nice field of view affect the view cone won't start from the player and point towards the mouse while hitting any objects it finds everything outside the view cone is hidden let's begin [Music] hello and welcome I'm your code monkey and this channel is all about helping you learn how to make your own games with in-depth tutorials made by a professional indie game developer so if you find the video helpful consider subscribing ok so this is what we want to create over here I'm controlling my player moving around and as you can see a very nice view cone pointing towards the mouse position you can see it interact with the object so there's a wall there and I cannot see behind that wall and I can right click in order to make it see further or short as you can see it modifies both the view distance and also the field of view over here you can see a bunch of enemies and as you see they are only visible when inside the field of view so if a wall is blocking them I cannot see them using this with a completely black outside mix for a very interesting effect so as you can see how this would be very useful for any kind of stealth or horror or strategy game you can see this effect in action in my very first Unity game survivor squad the whole idea behind that game and its sequel was to control a team of survivors and very carefully manage where each was pointing in order to make sure that your survivors cover all the corners so the field of view was a crucial mechanic and I still don't like those games because of it the game is included in the game bundle so go pick it up and play it to see how you can apply this effect to your own games also this particular effect can be used to showcase enemy view cones like in a game like commandos or Desperados and that's exactly what we're going to be doing in the next video so stay tuned for that but in here let's are all very simple and make this nice film the view effect that works as masks and interacts with walls and enemies alright so this is our goal let's get to it ok so here is our starting scene I'm controlling the player character with the keyboard and I can use the mouse in order to aim and shoot there are also enemies I can spawn and shoot and kill them just like that ok now we're going to do a whole bunch of ray casts and generate a mesh based on where those Ray casts hit so let's begin by making our field of view script over here in our project files make a new c-sharp script let's call it our field of now let's make a film the viewed game object and drag the script onto it alright so known here and let's first spawn a very simple mesh if you want an in-depth video on how to make a custom mesh through code check the video linked in the description that video covers everything you need to know about how much is setup so here I will assume you know the basics so let's start off by creating our local arrays okay that's the basic code again if you're not familiar with meshes go check out your video where you won't understand what all these arrays do now in order to display our mesh we need to go into our game object and then here we also need to add a mesh filter to hold our mesh any mesh renderer to render our mesh okay so then here we just get the component of type mesh filter and set the mesh to our mesh all right that you do it let's see any of those are nice about triangle okay so far so good alright now let's try to make a triangle but using our fov values okay so I'm here and let's define a float for our fo mean so we're going to set our film the view to let's say 90 degrees then we need to define the number of rays we're going to do so an end for the array count and let's say we're only going to spawn to raise the more rays we have the more defined our field of view won't be however it's also expensive to do a lot of race so we need to manage this carefully for now - will do and then we need to saw or a current angle which we're going to increase in our cycle so it float for a current angle and then we need to calculate how much we're going to increase our angle for each cycle in our loop so float let's call it angle increase and it's essentially our field of view divided by our number of bricks okay now we also need a view distance so it flows for the view distance and that's pretty much all the values we need so now that we have our values let's set up our arrays now in here for our since we're essentially going to start the origin so that's one vertex then we're going to have to raise so that's two more and our recount will not be including the zero gray so we're going to have the Ray count was one for the origin and plus one for the right zero so in this case with two rays going for a field of view of 90 degrees we're going to have one ray firing at zero angles then one at forty five and one at ninety so that essentially makes three vertices plus one on the origin all right now for the UV we're going to use the exact same thing so we can use vertices darling okay and now for the triangles we're essentially going to have as many triangles as we have rays however for each polygon triangle we have three values in here so we do recount multiply it by three all right this is the size of our race now in here let's first set our origin so the vertices on index zero is going to be our origin so let's actually also go up here and define a vector three for our origin and let's start off at factor 3.0 okay so there's our origin now let's make a nice 4 we're going to cycle through on our race and now in here let's place our vertex in the correct position so we'll find a vector three for our vertex and essentially we're going to place it on the origin and then we want to move it towards our current angle so for that I'm going to use a function from the you Tony as always you can download the utilities for free from in Tacoma comm and here in the utilities there is this nice function which converts an angle into a vector3 so if you want you can just write this yourself in your script so in here we call that function we pass in the current angle and we multiply the real distance all right so that's the correct location for this particular vertex now we need to place it on our vertices array so that means we also need to know the index so in here let's define an end for the vertex index and we're going to start on the next one since index 0 won't be the origin so here we set the vertices on that index to be this vertex ok that's our vertex position then we need to increase our angle by our angle increase so that it increases for the next second however here actually when you increase an angle in unity you are going counterclockwise when in reality here we want to go clockwise so instead of increasing let's decrease clockwise or counterclockwise is very important in order to make our triangles which is what we're going to do right now so here we need to set up the current triangles so we also need an int for the triangle index in this case we start off at 0 and then here we're going to set the triangles on our triangle index and first we set on the triangle index both zeros on the actual index we're going to start off every triangle on the origin so we start off on vertex 0 then for the triangles 1 and 2 the one won't go to the previous one so our vertex index minus one and the two won't connect to this one vertex index yep exam one like that ok so this might seem confusing but it all makes sense when you see it in action and here after we set all of our triangles we need to make sure to increase our triangle index and in this case we increase it by 3 so here every triangle won't be from the origin to the previous vertex to the current vertex and that makes a polygon try however in here since we were connecting to the previous one you can already guess that we have an issue here and the issue is this will cause an error if run on the first rate since the first rate doesn't have a previous vertex to connect me to so we're going to make sure that we only run this if the eye is bigger than zero and then we also need to increase our vertex index all right that you do it over here we have all of our films that make this extremely easy to modify so we can modify the field of view the origin how many ways we have our starting angle and the view distance over here we set up our vertices u these n triangles we sight on through all of our race we locate them on the correct position we generate the triangles and we move on to the next thing on for the next segment once everything is done we simply upload it to the mesh all right what's this and we should be able to see exactly two triangles that put together make up a 90-degree angle let's see and if there it is and exactly as intend to race was the origin right so here is ray zero then ray one and ray tube and if we pause we can actually look at the wireframe so here we are in the scene view go all the way up here select wireframe and there it is you can see exactly how the field of view is being generated so we're here is our origin this is vertex zero vertex one vertex to then the first triangle connects this one to this one to this one so makes a triangle and the second one connects this one this one this one makes another triumph all right awesome so right now this looks more like a triangle red than the field of view so let's increase the rate count to smooth out the rotation here so in here on let's go into our recount and instead of just two rays and let's try to have fifty okay let's see and if there it is our field of view mesh is now on what more detailed so you can now see very nice round and if we stop and look at the wireframe and there it is you can see exactly how each triangle is set up in order to make our overall shape right awesome okay so here we have our very simple base now as you can see if we run the game you can see a pretty obvious issue which is the feel of you is not colliding with the wall here so let's add object interaction and also in order to see I decide a material to make it half transparent so we could clearly see that over here our field of view is going past our object okay let's deal with that so back in our code here over here we are simply placing the vertex exactly on the position however instead of doing that we want to do a recap so we're going to do a physics TD and call raycast now we're going to recast from an origin so it's this origin then towards a direction so it's this direction and then towards a certain distance which is our view distance okay so this whole thing returns a raycast hit Q D and using that we can test it the brake acid TD if the collider is known if the collider is known that we did not hit anything so we can run this code in here so if we don't hit anything we set the vertex to exactly where it was on the maximum distance however if we did hit something let's place it exactly on the point where it was hit and for that the rake asset actually contains the exact point so Rick I said point and that's our vertex all right it's that simple and this should be working let's test any of there it is you can now see that it is colliding with that object so if we pause and look at it yep there's our nice shape it goes through there and then hits that one so it cuts off and then it goes past okay awesome now in here instead of creating our field of view just on certain let's do it on update so it constantly refresh it so over here on start and let's simply set up our mesh and set the mesh down there okay and then we make a front boy update okay so there it is very simple on start we create the mesh we set it on the mesh filter and then on update on every update we are constantly doing our race so now with the game running I can now go into the scene I can move it and there you go you can see how the field of view is changing however here if we spawn an enemy you can see a big issue that we have which is the enemy goes in and there you go the enemy is now blocking our field of view the reason is because our recasts are colliding with everything so it's kinda lighting with the objects but also with our enemies so we want to make sure we only collide with certain objects so for that we're going to use a layer mask if you want to know more about layers layer masks and bit masks check the video linked in the description here we're just going to use it and select only the objects layer so here I make a zero ice field or a and layer mask and then down here on our raycast simply use this layer mask just like that and I can go back into the editor and here on the field of view you can see the layer mask in here it's very nice and we can simply solve it so in this case I want the wrong which are on the objects layer so select it and now let's test and there you go the field of view is now still hitting the wall but it's going past the enemy so here I can move the enemy around on top of the field of view and it normally combines with all right awesome now so far we've been testing our field of view being commonly static in that position in order to keep things simple but obviously the field of view is meant to be attached to the player and looking at the mouse position so let's do that now for that let's go here into our film the view script now we're going to make two functions so then here we'll make a public void let's make one to set the origin and want to set the aim direction okay so here for the origin it's very simple we simply set it and then down here we use it as we were doing previously and down here for the set M direction with the given indirection we need to calculate our starting angle so we calculate our starting angle to be our aim direction so we need to convert the vector three into an angle so again there's a nice comfort function on the U Tony's here it is if you want to make yourself it just takes a vector three and returns a float for our Euler angles so we take that have to be passed in the aim direction and if we do this the starting angle won't be exactly on the aim direction whereas we want it to be on the middle so we simply subtract our current FOV divided by two F so let's also put the fov all the way up here all right so that's it here we set the starting angle then over here on our update we use it okay so these are our two functions now we need to calm them so let's go into our play files here is the player class now how this is implemented is irrelevant for the field of view all we care about is to use the player position and the aim direction so in order to call that on the field of view we're going to add a serialize field in here for our field of view script and then here is the update code so here we have our aim direction so it's in here that I'm going to call the fill the view set the in direction to this aim direction and then also going to the field of view and call set origin and passing the transform dot position all right so that's it again the other implementation doesn't matter all we need to do is call these two functions and since we're doing the Sun update let's go here into our field of view and set running this on update let's do it on lake update so first the player sets the origin sets the angle and then on the only update this one generates the mesh so finally we just need to drag the field of view reference like that okay let's test any of there it is you can already see the field of view following the player and looking at where the player is aiming and everything is still working so if I go to arts this yep there you go as you can see it is interacting with the object and that one right there and down here on these ones and yep it's working all perfectly correctly and it doesn't hit the enemy all right awesome now our code is set up in a very nice way to easily modify the various fov parameters so let's play around these values over here let's try putting the fov just at 40 and let's increase the view distance to let's say 80 any of their it is our field of view is now much tighter and it goes for much further so you can see just how easy it is to play around with these bumps so let's make it so that the player can easily swap between various f of ease so for that we just need to also add functions in here in order to be able to set both of these both the fov and the view distance all right there it is very simple we just have two more public functions okay so here it is very simple adding some button press on the right mouse button in order to toggle a shortened one let's see okay here we are and yep I start with a normal field of view now I right-click any of there it is the field of view is now much tighter but also longer so click again back to this one click and back to this one so this is kind of simulating as if you were aiming down sights so like this you can see further and like this you can see wider here is the code extremely simple when we click on the right mouse button simply flip a boolean and we set the fov and the view distance so you can see how easy this class is to use and here it is again swapping between both things right awesome okay so now all that's left is to apply our visibility effect we want the enemy to only be visible when inside the field of view and invisible outside of it in order to achieve that effect I'm going to use the scriptable render pipeline so we're here I have a lightweight render pipeline asset and as you can see it has a custom for a render data so we can see that and here we have three render features so the default layer mask won't render everything except the things on the layer mask the behind the mask and the black layer so let's see how those are used over here you can see the walls are on the objects as you saw with the raycast and over here the enemy prefab is on the behind mask layer and our field of view let's put it on the mask layer over here I'm using a custom material that doesn't really do anything it's just so I can easily modify the Alpha so here back in our renderer again the default layer mask is printing everything except the mask behind the mask in the black layer and here on the mask and on the behind mask here you can see on we're doing is messing around with the stencil so first the mask renders to the stencil buffer and we write with a certain value always and then on the behind the mask we're only going to render where this previous value was written so if we run the we can see okay here it is I'm putting your Porter's and the enemy down there is not visible and if I go there yep there you go the enemy's being visible right so everything is working exactly as he must so we create our mesh and the mesh works as a mask and if inside the mask the enemy is visible if outside he's invisible and now instead of having the worm like this as you saw there was another black layer let's see that one down is in here on the main camera I simply have a game object occupying the entire camera and this one is on the black layer and back on the custom forward render data you can see the black in there this one essentially does the opposite of the behind the mask so it only renders this one where the mask is not visible so if we run this there you go everything is black except on the field of view and again let's get rid of the Alpha on our field of view mesh so here it is with zero alpha you can now see our actual film the view effect so again I right-click and I can change the shape and there you go just like that everything looks nice and the enemy is right there but he's hidden and now I go and yep I can see him now alright awesome now the player like this looks a bit weird so let's make sure that he's always visible so for that I can simply go over here into the character and simply spawn let's say a sphere there it is with a sphere make sure that it's on the mask layer and if there's this fear as you can see it cuts a hole on the black sprite and if there it is so now I can see the player and I can see all the enemies only one inside the field of view and now with the entire wall black you can see that this looks very interesting so just like this he can imagine some sort of stealth or horror game and now with the enemies being spawned I can go around constantly looking there's one there no yep there's another one there and another one and yet there's one there right there hiding behind the box and yep there you go now here we have one final issue to take care of there is our field of view is working nice nice nice go down and yep there you go now it's invisible the reason for that is our render bounced essentially our field of view is trying to render a triangle in here but the origin of the film of view game object is all the way up there so once it goes past a certain area as you can see it goes to here and it's stopped doing visible so let's Amba all we need to do is down here when we assign the mesh we go into the mesh and set the bounds here just see very large bounds won't do enough so let's try okay so here we're on what's going way down here and see if the film TV disappears and it doesn't so now we can play around for the entirety of our map and there you go now I put the outside mask in a pure black and you can see that right now we have a very nice very interesting like a stealth or horror game effect there is all those enemies are being spawned and I shoot them and they are invisible if they are outside of my field of view so here we have our final film the view effect it is easily customizable so we can modify all the parameters like the feel the view number of rays view distance and so on so here for example by clicking you can see me swap between a field of view that is wider but a short distance or a tighter field of view but those for a long distance so this is simulating a very nice aim-down-sights effect if you want to see this effect used in a complete game then check out my survive squad games including the game bundle those games are all about controlling your survivors and managing each field of view to make sure you cover all corners personally I really enjoy it and several scored gauntlets is definitely one of my favorite games so go play it to see how you can apply this effect to your own games also this particular effect can be used to showcase enemy view cones like in a game like commandos or Desperados and that's exactly what we're going to do in the next video so stay tuned for that as always you can download the project files in utilities from unity code marcom subscribe the channel for more unity tutorials who's any questions you have in the comments and I'll see you next time [Music]
Info
Channel: Code Monkey
Views: 78,398
Rating: undefined out of 5
Keywords: unity field of view, unity field of view 2d, unity field of view raycast, unity field of view shader, unity line of sight, unity fov, unity line of sight 2d, unity view cone, unity line of sight fog of war, unity enemy fov, unity field of view angle, unity field of view cone, code monkey, brackeys, unity tutorial, unity game tutorial, unity tutorial for beginners, unity 2d tutorial, unity 3d, unity 3d tutorials, unity tutorial 2d, unity2d, unity3d, unity
Id: CSeUMTaNFYk
Channel Id: undefined
Length: 23min 35sec (1415 seconds)
Published: Sun Oct 13 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.