Shooting with Raycasts - Unity Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I already knew how to do most of this but I scrubbed through anyway, this is so well done and entirely necessary. It lays down so much of the fundamental design stuff that I wish I had figured out much sooner. Good work!

👍︎︎ 4 👤︎︎ u/Vextin 📅︎︎ Apr 20 2017 🗫︎ replies

So simple and straightforward, i love it.

👍︎︎ 3 👤︎︎ u/faxlombardi 📅︎︎ Apr 20 2017 🗫︎ replies

Nice video. Def gonna check this out when I get home.

👍︎︎ 2 👤︎︎ u/jcdragon49 📅︎︎ Apr 20 2017 🗫︎ replies

Loved the video, very easy to understand.

👍︎︎ 2 👤︎︎ u/Ryusaikou 📅︎︎ Apr 20 2017 🗫︎ replies
Captions
in this video we're going to have a look at shooting in unity using raycast I love you guys said that my previous video on the subject was getting old I just read watched it and yeah so we'll have a look at creating a gun script where you can configure stuff like damage range and fire rate will also add a muzzle flash and impact effect and even add an impact force to the objects that we hit so let's get started so as you can see I'm using a few assets here I'm using the medieval arena they create from the western props pack and the gun is from this site by weapons pack if you want to get any of these models for yourself you can go to dev assets comm I'm just going to click on the sci-fi weapons pack here you can check out the page and when you're ready you can select the price and hit the blue button is then going to download as a zip file that contains a unity package which is going to set everything up for you so if I go ahead and hit play you can actually see that we can move around the scene to do this so simply went into the project panel hit import package then characters and I went under the standard assets character's first person character and I dragged in the rigidbody FPS controller I simply renamed it to player 1 did that we have the main camera and as a child of the main camera we have our gun object and it's totally optional whether or not you want to have a graphic here you could just disable this and have all of your logic sit on the main camera but I think it looks a lot cooler if we can actually see the gun also when you put a gun graphic make sure to select the main camera and decrease the clipping planes normally these are set to a much higher value which will cut off the gun and we don't want that now that you've set up your gun graphic like you want it we can go ahead and add a new script let's call it the gun script it's a new script select C sharp and Nick create an ADD stop a click it to open it up in Visual Studio and the first thing that we want to do is delete the two using tags at the top and the start method we're going to need a few variables for a gun first off we want to be able to adjust the amount of damage that our gun will inflict to our opponent so we'll create a public float called damage and set it equal to ten by default we'll also want a range and let's default that to a hundred so in order to be able to shoot we need to get some input from the player we'll do that in the update method you will add an if statement that checks if the player has pressed the fire button so we'll go if input get button down and the button we want to check for is fire one remember fire one is one of the default buttons set up by unity and unless you change it is going to map to the left mouse button let's open up some curly brackets and in here we want to place all of our shoes in code I'm actually going to go ahead and wrap this in a separate function let's call that one shoot let's go down here and create it so they'll write void shoot open close parenthesis and the curly brackets now we can put all of our shooting code in here in order to shoot will be using ray casting this means that we will be shooting out an invisible ray starting at the position of our camera and then in the forward direction we are facing if the Ray hits something we can gather information about what we hid and if we hit a target we can damage it if we don't hit anything we know that we've shot into thin air and so we can just do nothing but in order to shoot a ray from our camera we need a reference to it let's go up here let's create a public camera and let's call it FPS cam then I'll shoot method we'll go ahead and create a new ray cast hit and this is a variable that we use to store some information about what we hit with our Ray and we'll just call this one hit info or hit for short so that off with the semicolon then to shoot out our ray will go physics dot ray cast and that's a million different ways to shoot out a rate as you can see here we can take in a bunch of different parameters our case is fairly simple we want to shoot out array starting at the position of our camera so we'll put in FPS cam transform dot position we want to shoot it in the direction we are facing so we'll put in FPS can dot transform dot forward we want to gather some information and put it inside of the hit variable so right out hit this means that unity will automatically put all the information we need into this variable and then finally and this is totally optional we can input our range so that if objects are further away than 100 units we aren't going to be able to hit them now this should shoot out array in the way that we want it and now we need to check whether or not we hit something this is extremely easy in unity all we do is simply use this inside an if statement because this function will return true if we hit something and false if we don't so we write if and then we wrap this entire statement in an extra pair of parentheses and then of course the curly brackets so now everything in here only occurs if we've actually hit something with our Ray let's begin by just displaying the name of the object that we hit in the console let's go debug that lock and the information we need is inside the hit variable then dot we want to get the transform of the object that we hit and we want to get the name so we go dot name now if we save this head until unity and make sure to reference our fps cam in my case that's going to be the main camera under the player we should be able to hit play if we now hit the wooden crate it sets wouldn't create and if you had any of the other objects it's going to display their names as well say the floor with the podium now this of course requires you to have colliders on the objects that you want to Ray cast against on the wooden crate here I've gone ahead and added a box Collider so we actually already have the core shooting in place but there are a bunch of things that we can add on top let's begin by making it a bit easier to aim by creating a crosshair to do that we'll right click in the hierarchy go UI and then image as the source image I'm just going to go ahead and select the knob but you can use any image you'd like and for the width and height I'm going to input 10 and 10 I'm also going to decrease the Alpha a little bit and you can of course make this black if you like that better I think I do now by default this should be in the exact center of our screen if it's offset you can always click here hold down alt and click in the center that should snap it right in place well then rename this to crosshair and that should be all we need to do there now it's time to have a look at how we can apply damage to an object in order to do that we need to create a script for the target if you're creating an enemy you should call the script enemy but in our case we just have a wouldn't create so let's select that add a new component and call it target let's go new script create an ad and double click to open it in visual studio let's again delete the two using tags and both the update and the start method now this is going to be a really simple script we of course need a health variable I'll make that a public float now default it to something like 50 we also need a function that will damage our target we'll call this function from our gun script whenever we hit the target because we need to call it from another class we have to mark it as public so we'll write public void take damage and this time we don't want to leave our parenthesis empty instead we want to give our function and argument an argument is a way to feed data into a function in our case we want to be able to specify a certain amount of damage so we'll create a float and call it a mount we then just finish our function and in here we're going to subtract our amount from our health so health minus equals amount and the amount is going to be equal to the damage of our gun in the case that our health reaches zero so if health is less than or equal to zero or enemy dies in our case our create shatters and of course happens in here let's just go ahead and create a separate function for that and we can put this into a separate function let's just call it die and down here we'll make it we don't need to be able to call this from another class so we'll just write void die and for now we'll just go ahead and destroy the object so let's call destroy game object if we say that we shouldn't actually get any errors but of course we aren't calling this function yet and so nothing is going to happen when we shoot we need to go into the gun script go down into our shoot function inside our if statement where we actually hit something and we need to access that script to do that we use hit transform which is the object that we hit dot get component we're going to find the target component on the object that we hit and we can store this in a variable the variable is going to be of type target and let's just call it target as well of course not all objects that we hit are going to have a target script sitting on them we might hit environment pieces vehicles or items we don't want to shatter so we want to check if we found the target component to do that we write if target is not equal to null meaning that we only want to do this if we've actually found the component if we have we can go target dot take damage remember we can only do this because we made the take damage function public and as the amount of damage we're going to send our damage variable so now when we save this head into unity we shouldn't see any errors and under target script we now have a health variable it's currently set to 50 and our guns damage is set to 10 so when we play we should have to hit our create five times in order for it to disappear we'll go one two three four five and it's gone now that's about a billion ways that we can spice this up let's begin by creating a muscle flash for our gun in unity as with everything else there many ways you can go about creating a muzzle flash what I've done is gone ahead and created a particle system that sits on our gun I'm just going to go ahead and simulate it here so you can see what it looks like it's just some really simple particles they're set to non looping a very small duration and life time and make sure to check off play on awake I've also gone ahead and added a point light that is controlled by the particle system just to give it a bit of extra oomph once you've created a particle system that you like we can go ahead and play it through code to do that we need a reference to the particle system let's go to the top here and add a public particle system and let's call it muscle - then in the beginning of our shoot method with a muzzle flash dubplate when we now save and go back into unity select our gun and drag in the muzzle flash that's at play and now every time we click the mouse it's going to play our particle and a muzzle flash is going to appear next up we can create a hit effect at the point of impact to do that we use another particle system I went ahead and imported the default particle systems by unity if you then go under standard assets particle systems and prefabs there's a flair particle that you can easily tweak to make a really good impact effect here's what I came up with after playing with it a little bit so now that we have an impact effect prefab we can go into visual studio add a reference to this as well and this time we want to reference it as a game object that we can instantiate it into a scene and we'll call this one impact effect of course we only want this to occur if we hit something so we can go ahead and create this at the bottom of our if statement let's write instantiate let's give it the impact effect and the point that we want to instantiate it at is going to be hit dot point which is the point of impact we also want to give it a rotation and the normal thing to do here is have the particles point out from the surface that we hit to do that we use the surface normal this is a three dimensional vector that is perpendicular to the surface which means that it points straight out of course I instantiate method doesn't take a direction to look in it takes a catania so to give it a quaternion rotation we go continue dot look rotation this is going to take a direction and turn it into a quaternion and the direction is going to be hit start normal let's then close everything off with the semicolon if we save this go back into unity select our gun and drag in our impact effect we should see that when we hit play we have this cool-looking impact and it always Orient's itself nicely to the surface that we shoot the only problem with this is that we are currently instantiating a lot of objects and during a game our hierarchy is really going to clutter up so let's just make sure it's a quickly destroy these after use to do that we need a reference to the object that we just spawned and we'll store that as a game object we call it something like impact game object and set it equal to the instantiated object then beneath that line we can go destroy and the object that we want to destroy is our impact game object and we want to destroy it after say two seconds now our object should clean themselves up we can also add a bit of force to a wooden trade when we hit it to do we need to have a rigid body on our crate then in our script just like we get the target we can simply add a line saying hit rigidbody and we have now accessed that rigidbody component the first off we need to check if the object has one so we go if hit that with your body is not equal to null let me go hit the rigidbody that add force this is allows us to add a force in a given direction now we could both use the direction we're currently looking in or the normal of the surface both are totally standard I'm just going to use hit dot normal and then make sure that the direction is going to go backwards and we can multiply this with some kind of force let's go up here and create a variable for that let's make it a public float impact force and let's the fold it to say 30 and down here we'll multiply with the impact force let's save that going to unity and we should now be able to hit our crate you can of course bump up this force to make it more visible currently we are able to shoot as fast as we can click the mouse normally you want to have a limit on how quickly you can shoot a gun and maybe you want your gun to be automatic in that case we need to define the fire rate let's go into our script create another public float and this one is going to be the fire rate let's just fold it to something like 15 then what we do is down here create a private float and this is going to be the next time to fire and we'll default that to zero so we can fire right off the back we then check here if the player presses the fire button and our current time so time that time is greater than or equal to the next time to fire if it is we want to shoot and we also want to set the next time to fire equal to our current time plus one divided by the fire rate this means that if our fire rate is four we're going to add 1/4 which is 0.25 onto our current time and so we're going to shoot in intervals of 0.25 seconds the greater the fire rate the less time between shots let's close that off with a semicolon let's also remove the down here that means that we can just hold down the mouse button in order to automatically fire let's say that going to unity and when I now press and hold down Mouse 1 we can auto fire awesome so the final thing that I did for the demo scene here was make the crate destructible I covered that in a separate video so if you want to do that for yourself definitely check it out it's actually really really simple so now we have everything that we need to create awesome looking shooting mechanics let's pretty much it for this video other video this Sunday on weapon switching so if that's something you're interested in definitely make sure to subscribe on that thanks for watching and I will see you in the next video thanks to us the awesome patreon supporters who donated in March and especially thanks to Derek Eames Kirk faithful Merrifield James Calhoun and Jason the Tito if you want to support the channel and become a patron yourself you would do so a patron account slash brackets thanks okay
Info
Channel: Brackeys
Views: 1,491,057
Rating: undefined out of 5
Keywords: brackeys, unity, unity3d, beginner, easy, how, to, learn, tutorial, tutorials, game, development, develop, games, programming, coding, basic, basics, C#, effect, shoot, shot, shooting, raycast, raycasts, raycasting, bullet, muzzle, flash, impact, hit, particle, particles, force, gun, weapon, rifle, pistol
Id: THnivyG0Mvo
Channel Id: undefined
Length: 13min 40sec (820 seconds)
Published: Wed Apr 19 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.