Unity C# Throwing a Ball Explained

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and in this video I'm going to show you how to do a simple throw ball game this can be useful for um throwing knocking down cans or something like a Pokemon go or maybe even a bowling game so let's dive right into it right now I have a pre-setup scene and you haven't missed anything simply just a small little wall I've made here with cubes they all have rigid bodies on them and then I've just simply designed this sphere as a ball Nothing Fancy on it and then a ball thrower so the way that we're going to be doing this is I'm simply just going to move the ball throw away into the exact position here where this ball is so I just basically make it a child the object not off the box but off the ball itself just make it a child object and then I'm just going to zero out the positions and then I'm just gonna then remove it and no longer a child off and just move this all the way out the way so then with the ball and the ball thrower so the idea here is to put the script on the box so I'll go ahead and make the Box completely see through here just simply by making it transparent and also turn off the Collider so there we have it now you can do this differently this is just the way I like to do it so that later on if I want to spawn more balls in I can spawn more in and simply have these ones delete themselves or just have the same one reset which then you can just apply the script to the ball directly with some modifications of course so now if we do um continue here we're going to go ahead and create a script I'm gonna call this my ball thrower and I'm going to place this on the ball thrower um game objects let's go ahead and drag and drop it and then let's go right into the now it pops up on my auto monitor let me move it over and here we are simple ball thrower script now we're going to need some variables let's go ahead and create them real quick I'm going to show you exactly what we're going to need um and real quickly let's go ahead and create them all right so these are the variables I've created and these are the numbers that I've I've found to be a little bit more of what I'm looking for but feel free to change this around if they're you know if you just want things to be different for yourself so a couple of variables up top here a few here and a few down here go ahead and pause your video and copy of this uh variables if you need to do well of course you need to do so all right now I won't be needing the other three other two using system collections here so I'm going to remove those from the top now that we have our variables all set up let's start with the first thing here I'm actually going to remove this component this function the start function so we can just focus from the top going down so we just have the start function for right now and we're going to start building on that and going down okay so first thing I'm going to need is I want to set up ball and this is just a function I'm going to call when the game start I like to keep these separate so I'll make the function here void set up ball just like so and now in this function I'm going to declare what exactly ball is supposed to be as you can see I made it private if you want to skip this part you can then make it public but follow along nevertheless I just find that this works best for me so I'm going to say game object ball or say yeah sure underscore ball is what I'll call it game logic ball is equal to game object right not get component game object and then we're going to find a game object with a certain tag and I'll tag it player capital P in this case player so I'm making it in a way that we can always have different balls later on in the future and then we're simply just going to take our ball variable and equal it to the ball underscore so all you got to remember to do is go back into your scene and make sure that the ball this ball here is tagged player you can see it's capital P so now the script will automatically Target that as your player and if anytime you want to spawn in another one that's okay you can just call this function again to set up all after that I'm going to go ahead and call a reset uh let's say reset the ball and I'll go down the line and make that function as well so reset um oops reset ball just like that I don't need the private so I'll go ahead and remove that now that we have the reset ball inside a reset ball we're gonna do a couple of things we're going to be resetting a few variables the throw the hold in and um you're gonna see we're gonna basically make sure we set everything that our floats to zero um angles back to zero and velocity to zero so just watch all right so I've set everything back to zero and then also the throw in the Holden to false which are these two so I went ahead and angle back to angle is a vector three so Vector three not zero um the start post and the end post is the vector twos so I went ahead and set those back to zero and then all the other uh variables that are floats I just went ahead and set them to zero when I reset the ball I also want to reset the ball I should go into the ball component so let's say get component and it will have a rigid body on it and we want to set that razor body back to zero as well so we can say raise your body dot uh let's say velocity and we set it to a vector three dot zero we'll resend the ball we want everything to go back to zero I do need to access the ridge body one more time because we want to then also set the use gravity to false all right this will reset the ball instead of calling or accessing the rigid body twice using the get component you can however just create a variable so we can do a rigid body variable call it RB and then we will have to do this only once right here inside of the ball setup when we Target the ball and Target this we can simply say um RB equal that all right or we just use the newly assigned variable like that as well so then down here we just got to say RB and then RB here without the get component without the get components there we go just like that so going forward in time we want to access the ball or raise your body remember just use RB now then let's start with picking up the ball actually be able to click on it and move it around the screen when you press play click on it and it follows the mouse that's not too hard to do not too difficult let's go ahead and do that we'll create a new function void and we'll call this pick up ball inside here we're going to create a vector 3 and we'll call this mouse posts because this will represent the mouse position so input.mouse position and this variable will represent that Mouse position right there and then so we want to make some changes to the mouse position when the pickup ball function is running first thing is a mouse position dot Z should equal to camera dot main remember the mouse is is two dimension on the screen up down left right so when you're trying to do something within a 3D World you need to go into the um the screen to World point but we're going to access first the near clip clip plane so that basically how close the ball gets to the screen and let's go ahead and I'm gonna do something drastic like 30. so that you can see exactly what this does we're gonna do the new position which is a variable that we have right here you're probably wonder what that is for just a temporary position that we use to place the ball at a certain spot in there the um in the world um that we used to like what I just mentioned about the mouse being 2D just place a spot in the world for that and so then we'll say camera dot main this is how you access that as I was saying it is screen to whirl point and then we're gonna use the mouse position finally where it's time to move the wall we say ball dot transform but don't forget to use the local position and say equal vector3 dot lerp we want a nice smooth smooth transition so we're using alert work simply needs the ball current position so basically that is the same as ball transform dot local position right here then comma the new position right which calculates the mouse in the 3D three-dimensional world and then we will say here for movement the speed basically I like to go with 80 and then times time dots Delta time okay now this when this is active the mall should follow the mouse along the screen we're going to take a peek of that in just a moment let's go ahead now into the update function inside the update function we're going to Simply do an if and you can say if Holden which is a um which is basically a Boolean that we've made right here we have a throw and holding so if holding if we've picked up the bomb we're holding it then what needs to happen we need to do the pickup so basically do this where the ball will fall the mouse again I'm going to show you exactly why this 30 is 4 and how 30 is a bit dramatic but I'm going to show you what it does now just for a quick quick with a check here if thrown if we've thrown the ball at this point we should be able to carry on with the rest of the code because we shouldn't be able to affect the rest of the code that's coming up because the ball is already thrown okay so there's no need for us to affect that code all right let's quickly let's quickly code the ability now to click and pick up the ball we'll just use raycast we won't use the on Mouse um unmasked down and almost out because I would use that if I was directly put the script on the ball but since I'm placing it on another object here we'll use um raycast detect that we've clicked the ball I will show if you guys request I will leave another you know I will leave another Link in the description with another script that you can just drag and drop on the ball itself and you won't need this all right so anyways return if we've thrown the ball so we cannot like click on the ball again until it is reset okay so if right we're gonna do a input and get mouse button down and that would be Mouse 0 which is our um left click or primary click you see if I click here click there and click there and click there that is the click so when we click down we can click anywhere on the screen we want to make sure that where we're clicking is actually on the ball so I'm going to create a variable here for Ray and Ray would simply be casting out from the camera into the world space so again screen point to Ray and from where the mouse input position right we're going to also capture the the raycast hit now let's just call that on the Square hit done deal now then here's where we do the Logics to test to see if we actually clicked on the mouse or on the wall the mouse clicks on the wall so we do physics Dot raycast and then we need to tell it where we tell it from where the array is out to where that hit was and this is infinite unless you put an option of how long um the ball is going to be relative close to the camera so I'm going to go maybe just a hundred um there in pixel I believe it's pixel could be wrong but 100 usually is pretty uh pretty good otherwise we'll shoot away from where you're clicking which is infinite all the way out or how many however many you determine right here so if you want to create some sort of game where if it's too far you can't click it then yes you can use this um number here this value to decide that all right now we're shooting out that way check to see if we hit so if the underscore hit yeah that means we hit something we're going to check the transform of that thing we hit so Hit the transform and see if it is equal to the ball dot transform or we can also just do like tag or or layer but ah just do it like this okay once that happens we will start our start time variable can't spell start time is going to start so we have a little timer here that starts to tick tick tick tick tick there we go start time um we need a start position as well start position equals where the mouse is right now so input dot mouse position if you're wondering start position and start time these are the variables that we've had up here start time and the start position which is start posts which is um a vector three so we need to know where we've started and if that's true then hold in equals true right and you can see here if Odin is true then we're picking up the ball which should be correct because we're clicking on the ball according to the raycast with this amount of code let's do a quick test you can see the results of what this number here does 30 f hit play Channel Mac to Unity game is playing there's no original ball rigid body on the ball my bad let's go ahead and add a rigid body and don't forget to uncheck the use gravity if you don't uncheck these gravity and you hit play the ball will then fall but the reset oh I almost forgot the reset is unchecked that for us so you can see it right here so that was actually pretty nice that we added that in anyways click on the ball and as I moved around you can see how far it is all the way down there right when you click the bar sort of disappeared and now it's following the mouse but it's all the way down there in that world space remember miles is 2D the ball is all the way down there in that world space now if you reduce that number say five hit save head back into Unity right ball is right here and then we can try to throw it now when you release the click the ball still follows the mouse so what we want to do is as soon as you release it we want it to snap back into this position so releasing the mouse requires us to check for the opposite of this this is on Mouse down button zero we need the on Mouse up for that button zero so you could do an else if here let's go ahead and do that so this is open for this this is the closing for that condition so we can attach it quickly else if and we're going to check now for input.mouse up for Mouse 0 like so and create the body I'm gonna go down one line like so just for cosmetics okay so then let's also do a end there is an end time the time has ended when we're done clicking and then the end post which is another variable that we made is wherever the mouse has ended in position this is all useful for calculating directions and the Angles and all that stuff just keep watching till the end you see how this all comes together we're going to also do a swipe distance which is a variable that's already made this will equal up to all we got to do is the end position minus the start position all right and position minus stock position then we just do the magnitude so now we're making our calculations based on starting and start time and end time and our start position and end position when we first click the ball the swipe time now is another one we need so swipe time will equal to not that swipe time will equal to the end time divided by or minus the start time so when you first clicked on it and when you release that is your swipe time which will help us with determine the speed of your flick all right while we have released let's go ahead and check to see if the swipe not distance but the swipe time is less than a very small number here which will let us know that you've done a nice little flick and the swipe distance want to make sure that you've actually moved the mouse and and into a a minimum distance let's say it's more than let's say 30. so you've actually done a nice little swipe there at that point basically you are you have thrown the ball or you're trying to throw the ball so this is um throw well basically what we want to do here is we want to calculate your speed it's not going to say calc um speed just something we're gonna do later so I just commented out calculate your speed and we want to calculate your angle we're going to make these two variables or these two functions soon but let's continue so at this point we'll tell the ball rigid body which remember that's RB and we just tell it to add Force in the direction of new vector um three in this direction the direction for the X will be calculated by our angle variable dot X and we will times this by the ball so speed the direction of the Y would obviously be the angle of the Y and we will minus this by the ball speed sorry so sorry we're not going to minus this but times it as well by the ball speed we're gonna make some changes to it later now the Z is going to be similar the same let's do a parenthesis here and put this and this into a parenthesis of itself just like so and then we'll do the same for these parentheses like so so hopefully that that makes sense to you and then in here um we'll do the same thing so the Z will be angle dot Z and then we're going to times this by 12 speed okay just make sure you guys understand what we've written here all this and a nice parenthesis that is the X all this why and z where is my open parenthesis there you go just like that so let me see here new Vector 3 okay everything looks good um what am I missing open okay we're missing one more closing parentheses here for that one there we go and that will do it all right so um let me just put a little space here so we can separate these which one is which looks like so then we have like so there we go so it's just easier to look at all right that will add Force to the ball next the rigid body again we need to tell it to use gravity and we tell it that will be true now because we've we want it to throw next hold in will become false because we've thrown it no longer holding it and then Throne which is the other variable is now true so this variable here throwing and holding they are key telling it when it's thrown when it's holding now here's the thing once this swipe happens that means we have thrown it but if we didn't if we'd simply release it we need an else so I'll simply put a little else here right and all we're going to say in the else is this one line we're going to put here is else and I'm simply just going to tell it to do the reset ball what does this do it resets the ball if we didn't throw it let's go into unity and check show you what I mean if I click on the ball it follows my mouse right as I'm click and if I release the click it should shoot back here and reset if I didn't throw it so to make that happen let me show you we're going to do the reset ball if uh and this is more than that so um the reset ball part should kick in if I didn't and I might have not saved there interesting so that's when this this one okay reset ball right here we'll do an invoke and we'll say one more time as a string though you write the name of the function so basically the name this function name right here put reset ball right there the comma and I'll put I'll put four F this means you're going to reset the ball in four seconds after it is thrown all right everything is saved reset immediately when we don't throw and reset when it's thrown all right let's give it a go I think save we're gonna go ahead and hit play that follows me if I throw try to throw it false to the ground and in four seconds that's a long four seconds something wrong a ball I guess gravity did yeah use gravity did reset so it did reset the ball um in the reset should you reset ball there's nothing that tells it to come back to that position so that's the only thing we are missing from our reset ball so that is that is important if we wanted to come back and reset so let's go ahead and do that all we got to do is somewhere here at the bottom we'll then say ball dot um transform dot position equal and then just say transform and then just say transform dot position because the script is going to be on this or it is on this it's going to reset back to that spot hit save head back into Unity and we're gonna hit play so now when I move it release it's not backs there move it release it's not like that when I throw falls to the ground there there's no like speed actually being applied four seconds later response perfect all right so these are all the mechanics needed to throw the ball the only thing that's missing is calculating the speed and calculating the angle based on the trail that's why we have the um where is it the ball speed and velocity and angle that's how we have these all As local variables and they're not private they're not created inside of the function itself okay so now we can go out of the update down here and we'll create the void and we'll call this calculate speed or calc speed which is this one right here so let me uncheck these uncomment these because these are what we're going to make okay this one doesn't exist I'll right click and tell the visual studio so just go ahead and generate it to get my calculate angle and calculate speed way these works are actually pretty simple let's start with angle this may be the difficult the most difficult one to understand but in angle we're going to give it all the information it needs to calculate the right angle instead of this variable notice that that's being used for the direction the the X the Y to Z and the ball speed all of it is being used angle is very important now to get this angle you must understand that the camera and the mouse the mouse on the camera is complete 2D as you're moving your mask across the screen so you got to be able to calculate that distance within similar to how we did with this if you remember what we did here the clip in planes and the making the ball show up all the way down there when we click basically the same deal so again screen two World screen to World point and then we say new vector 3. inside here the end posts dot y remember that end post is man post is the the mouse let's see when we when we first click Start post is the mouse and post is the mouse start an impost Mouse position so and here we're saying um the X and then the end um and post now for the Y or done dragon and then the Z well we're going to add Now 50 to it we gotta create I like 50 50 gives me more of a it's almost like if if you look at this sideways um where this line is the screen the mouse moves like this on that screen the ball is in here in 3D World so we have to give it like an angle to say hey you're going that way or that way so we have to give it a point to look at within the three-dimensional world once we have done that um let's go ahead and create a open and close parentheses here and calculate the camera dot Main and then the near clip plane one more time and add about five to that five is important um don't really want to take up your time with lectures or much but understand that the screen and the ball you move the mouse right here and the ball is going to use that as distance but what about in in the 3D World it has to see it that way not just in 2D so if this is a screen and this is the ball from a sideway View your mouse being like somewhere up here is going to equal to somewhere this way in like in the game itself in the 3D World so like that's that Z position so this is giving it to that Z position and height as well okay anyways on we go this is important to give us that Angle now for the speed cackling speed is pretty simple um let's say ball velocity equals the swipe distance divided by and we just put swipe distance minus swipe time just like that we want to make sure that it doesn't add speed to it when we're supposed to just be resetting so only when we've done a nice quick flick but guess what only when only when we'll say if um swipe time is more than zero make sure you don't get confused by that because this is checking if it's less than but it's still going to be more than zero just checking to see if it's a fast swipe well if it's more than zero at least you have swiped and it should then add speed um it shouldn't just not do anything okay um now that we have this velocity thing calculating speed by by swipe distance and time um we're simply just going to say ball speed will be equal to the ball velocity and I find that just adding a little extra to it helps so I'm going to say times um I do like a 40 or something just adding a little extra to it kind of help because this little swipe is a very small number and then setting the max velocity as you can see there is a Max variable for a max speed right here I set it to 40. um I'm gonna turn that up though so if uh just create a little function here a little collagic here let's see if the speed is and we're going to be less than or equal to um ball speed I'll actually say more than or equal to ball speed then you can say ball speed equals you know max speed or something just to check to see if you've gone over right we're at a little 40 to it to kind of like beef it up if you're going over that speed we're gonna set it to that speed if you want to just make sure that anytime you throw it goes to this speed just check to see if it's less than right so here we'll check if it's more than or instead of stat speed I'm going to do a little something here right and I'm going to check to see if it's less than the max speed and if it is I'm going to set it to um I'm just going to increase it so I'm just going to say ball speed plus equal I say ball speed yeah plus equal wow I give it an extra 40. that's all I'm doing there once we're done with that just go ahead and reset the swipe time equals zero and we're done I'll leave a link in the description where you can just copy paste it but hopefully you understand what's going on here now for a quick test and some changes that we're going to make so don't go just yet we're gonna make some more changes there's more changes to being made to make it react better right here but this is the the base of it the logic all right so um we're gonna hit play and I'll show you click move okay resets if I don't throw then when I throw boom it goes okay after four seconds reset it keeps spinning which I like that's fine throw with a NASA flick it throws now it's not going as much as it should so I find that there's small little tweaks that you can do to it right here to make it work even better um and again I will leave another script in the um description where you can just use a direct script put on the ball um completely up to you but this one is on the ball thrower and not this so anyways here what we can do right here to fix this is let's make some changes think logically when you're throwing a ball it does have some height but moreover it has forward speed right so as for the height which is this it's the height we want that to be about half and then this can be maybe doubled so first thing is I said the Max Speed I'm going to turn that up so I'll put that maybe 200 instead of 40. and now you see the ball does go right if I try to throw it it goes pretty far you know what let's uh let's actually let's actually do this um let's do this there anytime we're less than Max Speed it just goes to Max Speed simple as that right you can see what 200 looks like okay so you can see I took it out but a lot more height than I want so this isn't like a Pokemon go but if you want it then that's good for you so what I'm gonna do is cut that height in half by simply do a divide two then that's what a speed here I'm just going to take that speed and do times um two in fact I'm going to divide the height by three so it's taking that same speed that same high number but just reducing the the height value of it okay so one more time reduce this by three but then this one just multiply it by two I'll leave the code description for you anyways let's go ahead and hit play you can see what this looks like it's like so so now it's not as high I still I can still throw a high one if I wanted to but more of that speed is being applied to the forward and it's been applied then it is to the height now if you say oh I still wanted a little bit more height then you divide it by two instead and now a lot more for your speed would be applied to the height um you're still getting the same amount of speed applied to your Ford but just more now is being applied to the height and that is it for this video here is a complete look at the code after I've made my modifications this is the preferred way that I find it works best so these are numbers that I'm using feel free now that you understand how things work to make those changes and modify what you like to modify and as I had mentioned before you will be able to Simply take a script that I will leave in the description if you want to use a simple script here where you can just drag and drop it on the ball so I'll have that included just drag it drop it on the ball and then hit play and you have things working right off the bat just like that as well there are the pros and cons to each method so just pick the one that work the best for you thanks again for watching and I'll see you in the next one
Info
Channel: Online Code Coaching
Views: 7,284
Rating: undefined out of 5
Keywords: How to, throw ball, bowling ball, unity, throwing, tossing, lobbing, physics, throw and hit, unity tutorial, C#, script c#
Id: fljP8zJ75Lk
Channel Id: undefined
Length: 39min 16sec (2356 seconds)
Published: Tue Jan 03 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.