3 Ways to Shoot Projectiles in Unity!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video is sponsored by unity in this video we're going to look at three ways of shooting projectiles and three ways of doing hit detection in unity all methods are valid each with their pros and cons and which one you choose depends on what game you're making 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 alright so this is what we want to make over here is my player character and in here we have some nice targets and now if I click yep I'm firing a projectile now this is the first project on type it spawns a game object and moves z-transform then I can press a button in order to swap to the next projectile type and visually it looks exactly the same but it's working quite differently this one is working by using the physic system and now these two projectile types also have to separate hit detection methods now the first one is using a distance check and there you go it can hit all the targets and the second one is using a physics Collider and again visually they both look exactly the same so they both behave similarly and achieve the same result so these are the two normal projectile types and offer the last type which is not literally a projectile but rather it simulates a projectile this is the raycast method so I can shoot and yep there's the supposed projectile this one is using a break cast so it's an instant sort of projectile it gets fired towards the direction and there's a ray casted test if it hits something or not so here are the three methods of shooting projectiles that we're going to look at when using a transform to move our boat one using physics and one using a ray cast we're also going to try the three hit detection methods one using a dissin check one using colliders and one using ray cast as you're building your games you're going to need some assets and tools check out the grow your skills mega bundle sale happening right now on the unity asset store get over a thousand dollars worth of assets for up to 90 percent off so this is an excellent chance to get some assets at a great discount get some awesome assets who build the pure level some characters to play around with and lots of awesome effects get some tools to improve your work phone like in control for setting up multiple controllers and playmaker for visual scripting also included in the mega bundle is one year of unity and learn premium this is unities official online learning platform and it contains lots of completed projects courses and tutorials all efficiently certified by unity in teller and premium has over 500 tutorials in structured learning paths at every level to help you upscale and reach your goals so if you've been meaning to look at unity learn premium then this is your chance for the normal price you can get it through the bundle alongside tons of awesome assets in tools the link in the description is also an affiliate link so if you pick up anything through there you'll also be humping out the channel so check out the mega bundle sale get some awesome assets and tools and check out unity and learn premium thank you to unity and thank you to these ASPs for us for making this video possible go to patreon.com/scishow code monkey to get some perks and help keep the videos free for everyone alright so this is our goal let's get to it okay so here we are in our stirring scene I have my player character that I can move around I cover the basic character controller in a previous video and I can look around and shoot and I also covered how to aim towards a mouse in another video so check the links in the description to learn more now as you see when I click it plays the shooting animation but it doesn't actually fire anything alright so let's begin by creating our boat over here in the project files I already have a simple boat sprite so just drag it onto the scene and yep there's the sprite now let's set this up so let's make an empty game object to home our bullet and inside let's drag our sprite call it our sprite just making a parent game object so we can later expand upon our boat and also let's rotate the sprite to point it to the right which is unity 0 angle so in here just put minus 90 and yep example like that all right so here's our simple bullet game object now let's just drag it onto the prefabs folder in order to create a prefab let's rename it to PF boat alright so we have our boat prefab now let's instantiate it when we shoot and now over here in the scene I have a game object for my player it has a bunch of scripts in order to handle the animation movement and so on and then here we have the simple shoot projectile script let's open this up and it's in here that we're going to handle our shooting all of our code is set up in a very clean way with all the systems nicely separated so here we're handling the shooting while listening to the on shoot event that is fired by a base class so this is how we keep everything nicely separated if you want to learn more about events then check the video linked in the description where I cover them in detail now here we can simply spawn our bullet so for that let's first add a nice field for our PF bullet bought prefab and then in here we can simply call insensate instantiate our bullet prefab now we need the position and for the position over here the event comes with a on shoot event args and in there it contains the gun endpoint position as well as the shoot position someone spawned a bullet right on the gun endpoint position and for the rotation let's pass in quaternion identity alright so just like this it should be spawning the boat so let's just go into the editor and in here we just drag our bullet prefab reference and try the game okay here we are and shoot any of there you go there is a bullet spawn exactly where it should alright so we have our nice boat being instantiated now that we have the bullet being accentuated and let's actually move it so for that let's make a script to handle our bullets so in you see sharp script come with just bullet let's drag it on to our prefabs so just there and drag it okay okay so now in here in order to move our bullet we need to know which direction we should move towards so let's make a function in order to receive that direction let's make it public void come lick the our setup function and we're going to receive a vector3 for the shoot direction and now we can go back into our player script and in here we essentially it's bowling okay let's grab the in Senshi edit transform so our bullets transform and then we do get component to get our bullet component and we call our setup function and now in here we need to pass in the shoot direction so let's count like that and here factor three for the shoot direction and again over here on the event args we already have the two positions so they should position which is the target position so let's do that - the gun endpoint position and let's make sure that we normalize our vector alright so we have the issue Direction being calculated and we just pass it onto our bone so now the goal here receives the shoot direction now we just need to store it and then we make our normal update and on update and let's simply move the transform dot position towards the shoot direction x time down to time and let's also multiply it by a certain move speed and just like that very simple so we have the player which calculates the shoot direction then pass it - shoot direction on to the bone script and then the bone script stores that direction and simply moves towards it so if we test so here we are moving around and shoot and if there you go there goes the bullet going in that direction so shoot in there and yep go straight towards the mouse alright great so here we have our basic bone working however you can already see that we have two issues now the first one is that the bullet isn't rotating so if I should upwards if there you go you can see that the sprite is down pointing to the right and secondly the other issue is that the bone lives forever so if we pause over here you can see that we have all of these bones being in Senshi ated and they all still exist so this one for example is way all the way over there obviously we don't want our bouncing live forever so let's solve both those issues now first for the rotation it's actually very simple when we do our setup we receive the shoot direction vector so we go into our transform to modify our Euler angles and this case we're working in 2d so we're going to only be x and y at 0 and now for the Zen we need to convert this into an Euler angle and for that I can use one function from the utilities in order to convert the vector into an angle as long as you can download the code monkey Tony's for free from unity calm calm and here is the function in case you want to bounce yourself alright so just like this we should have fixed the rotation and now for the moment cleanup there are several ways that we can do this we could keep track of the distance that the boat has moved and destroy it after a certain distance or we can destroy it based on time using time approach is very simple here on setup we can just use the destroy function which is part of the monobehaviour and we're going to destroy this game object and this one takes the second parameter which is a time so here let's say after five seconds so after five seconds this game object won't be destroyed okay that should do it let's test okay here we are and first let's see the rotation so if I point upwards yep there you go it's now being rotated perfectly wherever I aim great and let's pause it over here we can see all of our bullets and they should all be destroyed after five seconds so I shoot them they get spawned and after five seconds they should become clean up and yep there you go they start being straight alright awesome okay so we can now spawn to shoot our bullets and after a while they get destroyed however right now they're not hitting anything so if I shoot at targets yep nothing happens so here now we have two methods of detecting hits we can decide to use the physic system or not let's first do it without the physic system so here in the editor there are the various target game objects they essentially just have two sprites and then over here they have the target script let's inspect this here it is it's a pretty small simple script now it's already set up in an interesting way we have a static list of one of our targets and on awake every target gets added on to the list so with this list we're going to have all of our targets and then up here we also have a nice static function it takes in a position and a certain max range and returns the closest target to that position within that max range so it cycles through all the targets in the target list Conal its distance and returns it closest so this is the same method that I use in the melee combat system that I made previously and now with this similar function we can use it to test for hits so let's go back into our boat script and in here on our update how we're going to do is call that function so it's going to the target in order to get the closest now for the position let's pass in transform position and for the max range let's define a certain hit detection and now this function returns a target so first we test if our target does not know so if we do have a target then let's just call the target damage function and once we do what's also destroy this game object alright so that should do it we test for the closest target to this position within a certain radius and if there is something then we're going to damage the target and destroy bolt let's test ok so here we are we can still move again so shoot normally all right then now if we shoot at the target and if there you go we correctly hit the target so our bullet is testing the position looking for the closest target within a certain radius and if it find something then we have our head awesome so we can now fire bullets and have them hit our targets and here you can see the first method for shooting projectiles by using a transform in order to move them and the first method of hit detection by cycling through our targets in doing a distance check now this method of hit detection has some pros and cons the main pro is it does not require the physics system at all so it works with a simple vector three position there's no need for any colliders or anything of the sort however the one downside is we're testing the distance against every single target if you have a small amount of targets and this isn't really an issue but if you have a lot then it can quite quickly become very expensive so let's look at the second method for hit detection by using the physics system so first here in the editor let's add a box Collider onto our target and let's edit it to put it right on top of the target okay just like that there's our Collider now we also need to add on our projectile so let's open up our bolt and in here also add another box Collider and again set the size yep just like that and now if you've seen the video where I covered simple collisions then you know that just like this it won't actually work in order for the collision to work we need to have at least one of the objects with a rigidbody so much added over here on our bullet we add a rigidbody 2d and now since we're moving the transform directly we need to make sure that this rigid body is set to kinematic then to make it move smoothly and let's interpolate and in order to not teleport between targets let's make sure that the collision is continuous and here let's also make sure that our bullet is a trigger alright so here we have both objects set up we have the bolt with a box Collider and a rigidbody and then we have our target just with a box Collider so now let's go into our boat scripts and then here the way that we handle collisions is actually very simple all we need to do is that the function private void on trigger enter to D we made the bullet that trigger that's why we're using the trigger and using enter means that it will be called once when the bullet enters into another Collider and we're working in 2d alright so this will be called when there's a collision in the physic system now we need to do is check if the collider that we hit was a valid hit so let's test if our Collider that get component of type targets if it is not known then we have hit a target alright so if our Collider does have a target component then we hit a target so we can't target damage and we destroy the bolt so that's it very simple now we can comment out the previous method for hit detection and just test this out ok so here we are in still shooting normally alright so far so good now let's shoot up the target any of there you go the colon either hits and we have our target hit so we can shoot all of our targets and all of our bullets are colliding exactly as intended awesome so here we saw the second method of hit detection we're using the physics system in order to test when a collision occurs then we test if we collided with a family target and if so we do our hit logic now the benefit of this approach is we don't have to test for collisions on every single update against every single target when it happens the physic system will not let us know so when dealing with projectiles this is probably the better approach for hit detection now let's look at the second method for handling the projectiles for that let's go and duplicate our prefab call this our bone with physics and now since we already set up everything to hand on physics collisions then everything is almost set up the main difference is down here instead of kinematic it won't be a dynamic rigidbody so we make it dynamic let's make sure the angular drag is set to zero as well as the gravity also set to zero all right so that's our setup not much different than the previous method now let's make our script so let's make in easysharp script call it our bullet physics and now in here let's also make a setup function where the direction so a public Boyd setup will receive a vector3 for our shoot direction and now when we receive it on our other method we were storing the shoot direction then using it on update in order to move our transform however in here we're going to use the physics system directly so instead of let's get component of our rigidbody 2d and then we use our rigidbody in order to call add force we're going to add a force towards our shoot direction and make sure that it's an impulse and finally since shoot Direction is normalized and let's also add a certain move speed all right so just like this our object should be moving in the world now let's just spawn this type of bullet so let's go into our player and let's duplicate to add a field for the bullet physics transform and here we're going to use the second method alright so just like this so it's essentially pretty much the same code as previously just with a different component and a different prefab okay so all this should work let's test ok so here we are and shoot any of their yo the bullet is still being spawned and flying towards a target so it's behaving pretty much exactly the same as the other boat except this one is being controlled by the physic system now we forgot to solve the issue with the rotation so let's solve that and then we also need to solve the hit detection so let's do those so we can pretty much copy the same code as in the boat so for example over here we have the Euler angles and the clean up after a while so we can pretty much copy the exact same thing and for the collision also pretty much the exact same thing alright so that's it now this should be working let's test ok so here we are in shoot and yep there goes the bone shoot to the other side and yep the rotation is all correct now I should add a target and if there you go we have our hit detection working so we can shoot the moments hit the targets and if not then they keep going and they get cleaned up afterwards alright so everything is working correctly awesome so just like this we have our second method of handling projectiles this one is using the system in order to handle its movement and we're also using the second hit detection method which is also based on physics so we have our bullet correctly working exactly as intended all right so we looked at two methods of shooting projectiles and two methods of hit detection first shooting by moving the projectile with the transform and secondly by using the physics system in order to move it and for the hit detection we tested the distance against all objects and we also use the physics system in order to handle our collisions now let's check out the third method for shooting a projectile and the third method of hit detection now this one isn't technically a projectile but rather a way that you can simulate a projectile in your game I'm talking about having an instant projectile so as it's fired it instantly either it hits or misses for that let's make our script so we need C sharp script we're going to call it our bonus rate cast and now here our supposed bullet is just going to be an instant so we're not really going to have any object at all so since we're not going to instantiate this class as an object then let's make it a static class and get rid of model behavior all right now let's make a shoot function so a public static let's return void and call it shoot we're going to shoot take a vector3 for the shoot position and a vector3 for the shoot direction so we're going to shoot from this position towards this direction now in here we do a simple recap so we are into the physics 2d in order to do a recast start on our shoot position and go towards issued direction now this will return a raycast hit 2d and we can test if we hit something by checking if our weak acid 2d collider if it is not known then we have a head so if we hit something let's test if it's our target so you try to get the component of target on the hit collider and if we have it then we have hit a target so let's cause some damage all right so that's pretty much it for making a simple array cast now back in our player here instead of using this other method let's use our recast method so we go into the bullet ray cast in order to convey shoot function press in the shoot position and our shoot direction alright so that's it very simple let's test ok so here we are and shoot and right now there's no visual so you can't really see anything but if we shoot towards the target if there you go we can indeed cause some damage so we hit target shoot down and shoot down and yep just like that so our ric acid is working now for the visual we can use a nice boat race visual that I made in a previous video quite a long time ago check the link description if you want to learn how it works do I set that up it is very simple I just use the weapon tracer class in order to create a weapon tracer from this gun end point position towards the target position so let's say the mouse position let's see okay here we are in shoot nè up now we have a nice round tracer visual so we can now shoot all of our targets and yep we can now see them again I cover this in a previous video so check it out to see how it works and just like this we have our third method and fully working instead of having a moving object what we have is an instant either hit or miss so depending on what game you're making this might be the better approach compared to a moving projectile all right so here is our final scene right now I can click and yep I'm shooting projectiles this is the first time that is firing a moving projectile by moving the transform it's also using the first method of hit detection by checking the distance against all targets and now by pressing a button I am now shooting the second type of projectile now originally they are exactly the same but functionally quite different this one is using physics in order to move the boat and it's also using physics in order to handle the hit detection and I'll finally click another button in order to use the third method so now this one isn't really a moving project rather an instant shot it's done using a recast and it checks instantly whether it hits something or not so just like this over here you have three methods of shooting projectiles that you can use in your game now go ahead and pick the one that best makes sense for your game design check out the grow your skills Mega Man on sale happening right now on the unity asset store get over a thousand dollars worth of assets for up to 90 percent off so this is an excellent chance to get some assets at a great discount thank you to unity and thank you to DS ASPs forest for making this video possible go to patreon.com/scishow to code monkey to get some perks and help keep the videos free for everyone as always you can download the project files and utilities from unity code Montcalm subscribe the channel for more unity tutorials post any question have in the comments and I'll see you next time [Music]
Info
Channel: Code Monkey
Views: 144,169
Rating: undefined out of 5
Keywords: unity shoot tutorial, unity projectile tutorial, unity shooting 2d, unity hit detection, unity shooting projectile, unity bullet physics, unity bullet, unity projectile, unity hitbox, code monkey, unity targeting system, brackeys, unity tutorial, unity game tutorial, unity tutorial for beginners, unity 2d tutorial, unity 3d, unity, game development, game dev, game development unity, unity 2d, unity 3d tutorial, programming, coding, c#, code, learn to code, learn programming
Id: Nke5JKPiQTw
Channel Id: undefined
Length: 23min 7sec (1387 seconds)
Published: Thu Mar 12 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.