2D Shooting in Unity (Tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
when it comes to shooting in unity there's really two ways to go about it you can do it using prefabs or ray casts and which method you choose depends on what you want to achieve if you want your player to shoot bullets that travel through the air and takes time to reach the target using prefabs is probably the way to go with this method we basically create a bullet prefab and then spawn in a copy of it every time we want to shoot we can then apply forces to the bullet in order to make it move and check to see if it collides with anything in which case we can make it explode and apply damage another way to make your player shoot is by using ray casts instead of your bullets traveling through the air we instantly shoot out an invisible line that checks whether or not we hit anything in that direction the result is a much quicker and precise shot like we see in modern first-person shooters like Call of Duty or counter-strike the two methods are actually very similar we use the same code for triggering the shooting and the same code for applying damage so with that explanation let's get right to it but first let's not jump the gun on this one this video is sponsored by Dennis Ventura Dennis is an awesome game dev tutor who's just launched a new course on udemy the complete c-sharp master class this course will make you completely comfortable writing code in c-sharp and using it for programming your own games in unity it will give you knowledge on many different aspects of c-sharp and teach topics like databases link and WPF and much more at the end of the class you will even have made three games on your own if this sounds like something you're interested in simply click leave in the description to get started and get a discount all right let's start shooting no matter what method that we'd like to use there are a few things that we need to set up one of these is that we need to create a fire point and a fire point is really as simple as it sounds it's just the point from where we want to fire our bullets so if we go ahead and select our player here and right-click on him we can create an empty object and we can then take this object and move it to the place that we would like to fire from so in my case I'm going to move it just outside the barrel here we then rename this object to fire point and now if we take our game view and dock it to the side here and play we can see that as we move the fire point indeed follows our player and if we move to the other direction it so flips however we can also see that the direction of the fire point isn't actually changing and this is a problem because if we try to shoot using this we would fire to the right when we are facing right and we were also fired to the right when we were facing left and so we would hit ourselves and that wouldn't be too pretty and the reason for this it's actually a mistake that I made in the character controller if you're using another movement script this might not happen to you but so those of you who followed our guide on 2d movement we need to select our player and find our character controller 2d and if we open this up it's a really big and complicated script but at the very bottom we have some code for flipping the character and in here I thought it was a good idea to flip the player by inverting the scale on the X but instead it would be much better if we simply rotate the player so let's replace this entire piece of code here with transform rotate and then we want to rotate by a zero on the X 180 on the Y and 0 on the Z and that should do the trick so now if we go and play select our fire point we can see that as we move to the different sides the direction of our fire point is also flipped awesome so now we're ready to start creating our weapon and to do this we'll select our player I'm just gonna collapse the script again let's hit add component and let's type in weapon we want to create a new script let's hit create an ad let's double click it to open it up in visual studio and for now this script is actually going to be really simple we can go in and remove the start method and in step we want to create a reference to our fire point so that we can use it later so in here we'll write public transform and let's call this variable fire point then if we save that we can go into unity and we can also simply take our fire point and drag it into this empty slot and at this point we're ready to start shooting and of course the first thing that we need to figure out is when to shoot so inside of our update method let's create an if statement and what we want to check for here is some player input so we go input dot get button down so this is triggered whenever we push a button and the button that we want to look for is fire one will then close the parentheses and open and close some curly brackets and now every time we press the fire button we want to go ahead and shoot and this is not a function that unity has this is something that we need to create ourselves so let's go down here under the update method let's write void chute open and close some parentheses and some curly brackets so now every time we press the fire button it's going to call the shoot method and everything inside of these two curly brackets is going to be executed so this is where we'll put all of our shooting logic if you want to change what button to press in order to fire you can always go into unity go edit project settings input and find the fire one at the top here and we see currently the button to press is Mouse zero which is left Mouse but you can change this to anything that you'd like I'm gonna change it to space and at this point what we need to do next is going to depend on what method you choose let's start by focusing on prefab shooting so here we first want to go ahead and create a bullet let's save the script and head into unity and in here we want to first create a sprite so that's right click in the hierarchy go to the object and select sprite and the sprite that you want to use here is completely up to you I'm just gonna go under sprite here and search for shot and have this pretty cool shot - sprite I think that looks pretty good and then gonna take this object and rename it to pull it and there are a few things that we need to add to this object the first one is a rigidbody 2d this object will apply physics to a bullet and allow it to travel through air you can play around with these settings to get your bullet to behave in different ways now I don't want any gravity on my bullet I just wanted to travel in a straight path so I'm gonna set gravity scale to zero I also don't want it to be able to rotate in any way so I'm gonna go into constraints and freeze the rotation and finally I really recommend setting collision detection from discrete to continuous this is gonna help the bullet detect all the objects if it's traveling really quickly now the next component we need is a circle Collider so let's hit add component and search for circle Collider 2d I'm just gonna open this up and check that the collider is pretty close to our sprite I think that looks pretty good I'm also going to mark this Collider as a trigger and this is because I don't want my bullet to bounce around the environment I just wanted to notice when it hit something and then explode but you can definitely leave it as a normal Collider if you wanted to keep bouncing around so now we can take this bullet and turn it into a prefabs let's drag it from the arc into our assets folder and we then deleted from our scene so now we have this bullet prefab that we can make copies from let's go into our weapon script and let's create a reference to this object so we'll create a public game object let's name it bullet prefab and then inside of our shoot method we simply want to spawn a bullet into our world remember whenever we want to spawn an object we use instantiate we then feed it the object that we want to spawn so in our case that's our bullet prefab then we need to choose where we want to spawn it we want to spawn it at fire point dot position and then with what rotation and we want to use fire point rotation so we close that off with HTML colon and now if we save this and go into unity and select our player we can see at the bottom here we have the bullet prefab slot here we can take a bullet prefab and drag it in there and now if we play and try to shoot we can see that we are indeed instantiating bullets into a world of course this bullet currently aren't going anywhere but they're definitely there next we can go to I'll pull it and create a new script on this bullet let's just call the script pull it let's take crane add and open it up in visual studio and what we want to do in here is actually really simple in fact we don't even need an update method all we need to do is that right when the bullet spawns so inside of the start method we want to tell the pilot to fly forward to do this we need a speed so we'll go up here and create a public float speed and set it to something like 20 and we also need a reference to a rigidbody since it's our rigidbody that controls our bullet so create a public rigidbody 2d let's just call it RB then inside of our start method we can tell a rigidbody to move so RP dot velocity the velocity is our current speed of the rigidbody on the three axis and we want to set this equal to the forward direction so transform dot and we don't actually want to use forward here because that moves on the set axis and we're making a 2-d game so we don't use this set axis at all is that we want to use right and we then multiply this with our speed so we're basically just saying hey rigidbody please move right according to our speed and if we save this we can see that we now have a speed variable that we can adjust as well as a slot for our rigid body that we can simply drag in and now if we play and try and shoot we can see that our bullet indeed does move forward awesome of course the next step is to have our bullet actually register when it hits something and if we hit an enemy we want to apply some damage to do this we go into our bullet script we used a really handy function in unity called ontriggerenter so we'll write void on trigger enter 2 D will open closed some parenthesis and some curly brackets and of course as the name suggests this function will be called whenever something enters our trigger in our case whenever out bullet hits something and when that happens we want to do some different things we could for example destroy I'll pull it and maybe before we do that we can print out the name of the object that we hit but in order to get some information about the object we need to go up here and add an argument we want to add a Collider 2d and we'll call this something like hit info because it will store information about what we hit then inside of a function we can go debug log in order to print out a message and we want to print out hit info dot name so the name of the object that we hit if we save this and go to unity and play the game we then shoot our enemy and you can see as soon as our bullet hits our enemy it prints out enemy pretty cool and of course if we shoot in the opposite direction nothing happens because we didn't hit anything awesome of course we don't just want to print out enemy we actually want to damage our enemy and currently on my enemy I have this box Collider as well as an enemy script and this is a fairly simple script that you can easily just copy from the screen here what we're doing is just giving our enemies some health and then we are adding a function that allows it to take damage of course we want to specify how much damage so it takes in an argument with exactly that we then subtract from our health the amount of damage specified and if our health goes below zero well then we want to die so that takes us down here and this simply creates a death effect as well as destroys the enemy fairly simple stuff the only thing to take note of here is that in order to trigger this take which function I've marked it as public so that we can now go inside of our bullet script and called it from in here so what we want to do here is go hit info dot get component of type enemy so we try and find an enemy component on the object that we hit of course we aren't always going to be hitting an enemy so we're not sure that there's gonna be a component there and because of this we want to store this in a variable the variable is going to be of type enemy and it's just call it enemy also and right after here we want to check if enemy is not equal to null so if we actually found an enemy component on the object that we hit well in this case we can go enemy dot take damage and call the function that just showed you and here we can input any number we could put 30 damage 40 damage whatever you'd like or we could go to the top and create a variable for this so we'll create a public integer let's call it damaged and set it equal to 40 by default and then we can simply input our damaged variable down here and now we should see that whenever we play and shoot our enemy the health of our enemy gets reduced and once we reach zero or enemy explodes super coal and if you want to make this look even cooler we can create a tiny impact effect whenever a bullet collides with something in fact I've gone ahead and prepared a prefab here called impact effect and this is just a sprite renderer with some animation let me just add it to the scene here and play it back so that you can see very simple I've also gone under the animation and made sure to disable looping so inside of our bullet script we could create a public game object impact effect and then whenever we hit something we could simply create an impact effect so instantiate impact effect the place where we want to create it is transformed our position and transform rotation let's save that going to unity select our bullet and now under our bullet script we now have an empty impact effect let's drag our impact effect prefab under there hit play and now every time we hit our enemy we can see a tiny impact effect gets created and the same thing if we hit anything else like a platform pretty cool and also we can delete this again so that is how you can do prefab based shooting now that's wine time back a bit and see what we can do with break casting so this time we have no bullet prefabs flying around instead we do everything inside of our weapon script which currently looks like this and of course the first step to ray casting is sending out a ray to do that we use physics 2d dot ray cast and this will send out a ray from a point and then in a certain direction and the point that we want to fire from is of course fire point position and the direction is fire point dot right and this will go ahead and send out a ray it's really that simple to do of course we need to store some information about what we hit if we hit anything at all and to do that we'll go ahead and create a variable here called ray cast hit 2d and we'll call it something like hit info because it stores information about what we hit then right underneath here we can say that if hit info and this is just a very simple way of writing if we hit something well then we could for example print out the name of what we hit so we could go debug that log hit info dot transform dot name now if we save this and go into unity and hit play and try to shoot in the direction of our enemy we can see that a prints enemy whereas if we shoot in the opposite direction nothing happens so indeed this is working but it's currently completely invisible and it's not even damaging our enemy in any way luckily applying damage to our enemy in this way is just a simple as with rakish shooting in fact the code is pretty much identical first we take the hidden foe object we go under its transform and try to get a component on the object called enemy of course we're not always going to be hitting an enemy so we want to store the result of this in an enemy variable I will just call it enemy as well then we'll check if we actually hit an enemy so if enemy is not equal to null well then we can call enemy dot take damage and input some damaged amount and the last time we put this code on our bullet script but now we simply have it here in the same script so we'll also put our damage variable here let's go public int damage and set it to 40 by default and let's then simply pass that in down here and now if we play the game with our enemy selected and try and shoot we can see that the health does indeed go down and when it reaches zero our enemy dies but again this is totally in this we want some kind of graphic showing what's happening so we could add an impact effect just like we did with Ray cash shooting and it's really just a symbol we create a public game object call it impact effect and then if we hit something we instantiate the impact effect at the point that we hit so hit info dot point and the rotation here doesn't matter so we'll simply use catonian dud identity which is basically just a very fancy way of saying no rotation and so we could select our player and drag our impact effect into the slot and now we still can't see any kind of bullet but we are able to see the impact effect itself so the last thing that we need to add is some visual feedback showing where we shot and for this I really like to use a line so we'll right click here and go and do effects and create a line and by default this is not going to be visible and that's because of a couple of things first of all we want to go to the order in layer here and bump that up to make sure it's drawn on top of everything else and also if we go under positions we can see the two positions that currently make up our line it goes from 0 0 0 to 0 0 1 and so it's only changing in the z-axis which we can't see from a 2d perspective so instead let's change that to 0 and try and move it on the X of course we can also adjust the appearance of a line if we go under color we get this gradient editor where we can adjust the color over the length of our line so if we want it to tend it in any way we do that there I'm just gonna leave it white we can also add some int gap vertices if you don't like it being completely square just to round it off a bit and finally we can adjust it with by simply dragging on this line here so I think something like this looks pretty nice I want it to be fairly subtle we can also go to the top here and tell it to use world space so that we can't really move it anywhere unless we change the positions in our array now let's take this line and drag it under the player and let's try to control it through our script first we need a reference to it so we'll create a public line renderer let's just call it line renderer then whenever we shoot and hit something we want a line to go from the point where we shot to the point where we hit so we can go line renderer dot set position and we want to set the first position so index 0 - fire point dot position well then set our end positions line renderer that said position one to hit info dot point and that should work just fine however we don't always hit something and in the case that we don't hit anything we just want our line to continue infinitely in space or at least give the appearance that it does to do that we'll use the same code so we'll copy it and then create and felis to these if statements or in the case that we don't hit something we can use these same two lines we want to set the start position to our fire point however we don't have an end position so instead we'll use fire point dot position and then add on to that fire point dot write x say a hundred so it's those of you who aren't too familiar with vector math basically what we're doing here is we're taking the start position and we're just shifting it 100 units forward so now if we save that and select our player and drag in the line we can see that whenever we fire our line will be drawn between us and the point that we hit pretty cool of course currently our line is always visible to change this will select a line and disable the line renderer and then inside of our script whenever we shoot we want to enable it so we'll go line renderer dot enabled equals true we then want to wait for a very tiny amount of time in fact we only want to wait one frame so we'll wait one frame I'll show you how to do this in a sec and then we want to disable it again so a line renderer dot enabled equals false and the way that we wait one frame in unity is actually fairly simple however we can't do it inside of a normal function instead we need to turn this into what we call a co-wrote team and curl teams are fairly simple to use but their syntax is pretty scary so just right after me for now instead of void here we'll write I in numerator so now we've turned it into a routine we can't just call it the normal way instead we need to add start co-routine because we want to tell unity that it's a kuroh teen and we want to start it and then inside of the parentheses we'll put our function and so now we can go down here and we can wait a frame and to do that we write yield return zero again how co-routines work is the subject for another video for now just right after me and of course have a link to where you can learn more in the description and now we can simply save and head into unity and maximize our game and everything should be working so let's try and fire and indeed everything is working awesome that's pretty much it for this video if you enjoyed it make sure to subscribe and bring that notification bell so you don't miss the next one also make sure to follow our new Instagram for updates and behind the scenes stuff also don't forget to check out the complete C sharp master class using the link in the description on that thanks for watching and I will see you in the next video thanks of the awesome patreon supporters who donated in August and a special thanks to Alexander player simmer io cheater 3d infinity PPR - VR systems Sybok mommy Thirteen's kirk personify thanks so long Lilith Clinton Vince Kuya Ronan Tynan Sullivan for presea Timah for the park James P Bruins cat now Kiyosaki Gregory Pierce Larry tweet cure Swedish key James Rogers propfan Robert boon Anthony patent and Erasmus you guys Rock
Info
Channel: Brackeys
Views: 934,338
Rating: 4.9551845 out of 5
Keywords: brackeys, unity, unity3d, asset, assets, model, texture, models, textures, material, materials, beginner, easy, how, to, howto, learn, course, series, tutorial, tutorials, fix, tip, game, development, develop, games, programming, coding, basic, basics, C#, 2D, 2D shooting, shoot, 2D game, gamedev, shooting, bullet, prefab, raycast, raycasting
Id: wkKsl1Mfp5M
Channel Id: undefined
Length: 21min 11sec (1271 seconds)
Published: Sun Sep 16 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.