MOUSE AIMING with IK in Unity - including basic platform movement and physics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back everyone so I've been doing some blender videos for a while and I thought it'd be time to do some more unity stuff as well so I'll be mixing things up but these are more speed modeling and things like that I hope you watched that last video that I made it was a Star Destroyer that I put together in ten minutes it freaked me out a bit timewise and now I'm gonna try to up the game next time so if you remember from last summer I released some videos about a platformer project I was working on had a bit of fun with this robot guy running around platform shooting things up I was using some inverse kinematics there for the arms in the aiming but I used a third party asset called final I K which also has a plugin for aiming I K and that's a really really good asset and I do recommend using that one but I also had a YouTube visitor a fan subscriber I don't know Matt Matt's his name is and he suggested that I'd make a video about doing some inverse kinematics aiming from a platform perspective so since I had some of the code already prepped I thought I'll put together a video about that a bit of a how-to and I want to be able to do it without using any third-party assets as well so in this video I just modeled a little cowboy guy you can see him on screen now probably it's just like a really basic low poly and I rigged the character as well and did some simple animations did a walk cycle and just some like an idle stance and some gripping and things like that aiming what I'll do now is I'm gonna bring that into unity and then having just run around a little bit to create a simple script to have them go left and right on the screen like a platformer and do some jumping and then most importantly I want to add the day.i a mic a script as well not only just aiming with that with your hand at a target but also looking at the target with your hands I'll go through the process now I'll be switching the camera around a little bit so I can do this properly and I'll try to edit it so it's not gonna be too too boring and dry out for you also check in the description below if you want to go straight to the ika art where I do the inverse kinematics you can just skip forward so I'll put expand a little of description below and click on that little hyperlink to the right position I've actually created this project once before and I've started a new brand new unity project so I can recreate the whole thing so it'll make it easy for you to follow along hopefully and but I will be dragging some of their assets that I've created from my old project in but I'll talk you through the process and again if you want to see the modeling and the reading in an animating of a character that the cowboy recorded for that but you can check my channel history and you'll find some videos about how to do that so if you want to check those out before and do that and then come back to this video first thing I'm gonna do I'm gonna create some some tidiness here so let's create a folder called meshes and then I'm gonna bring in this cowboy that I created and basics it's an FBX file that I created in blender and it's got a few animations here as well like the only ones I'll be using now really is the walk here like a walk cycle and also the idle pose here I'll be using that one that's pretty much it I think the rest I'll do with inverse kinematics let's drag him into the scene straight forward that'll just create him here and then I also prepared just a simple material texture here so let's create a new folder here and call this one materials so I'll include textures here as well and I've got a simple PNG file here as you can see it's super tiny it's only four by four pixels so for that to work let's actually create the material layer first as well so I'll right-click here create material and then let's call this material cowboy if I can type and for this one we need this texture if I drag this on now you see that colors are all funky and that's because I need to do this with the texture we need to switch the point because we don't want it to interpolate and also we want to switch off compression to none and then that's when the colors pop it's because it's such a small texture that it's only these individual pictures of pixels that we need I've also prepped here so I've modeled a little pistol or revolver and a hat so I'll bring those two in by dragging them into my meshes folder here all I need to apply that that's fine so let's bring the gun in here and let's slap the same material on that one and then we can also bring the hat in and put the same material on that if I hold Alt key and click here you'll expand the whole hierarchy here and what I want to do now is I want to put the hat on to the head it does no good on the floor so I'll drag this one up and put it on head end and then here we just reset their position and one the Hat is in the correct place and then same for the gun we want to keep that in his right hand so let's put it there there we go it's in his hand now I just reset the transform there to zero zero zero based on hand we can move it a little bit there so that's it we've got got it set up now and what we need to create now is an animator so if I press play now then basically nothing will really happen here so we need to set this guy up so okay let's add that we already have an animator on here but we do need to create here so we'll call this one okay the new folder called bounding made four then where I click here and create a new animator controller and call it cowboy and double click that one and then basically we want him to default into an idle pose here and that's gonna be the entry and the default one and we don't have to do much more to that at the moment so but we do need to click on the cowboy here and then drag this newly created animator controller onto the controller here and now he is so I have to do that when I'm not in run so otherwise it'll reset so let's do this again drag this one on today and when we press play now that is standing in its idle position it didn't loop now and it's because I've imported this cowboy and I need to go to the animation tab here and then on the idle I need to do loop time another thing we should do is we should switch this rig to humanoid let's configure the avatar here everything is correct pretty much on the bones that I named on my mesh apart from the chest is not defined so let's pick that chest here that one everything else is defined here so that's good let's apply animator and let's press play again just to make sure and it's now looping so you can see that is feet are moving a little bit that's a real pain and what you can do to compensate for that is that you can go back to the animation and I switch off animation compression that can help obits plus we can go into the idle pose here and then let's switch to original here for all of these and then bake into posts for all the mo positions and rotations and then apply that one and now there'll be some less movements on its feet there they're not they do is still a little a little jump but it's not really going to be noticeable when it's in a platformer game like this okay so we've got Tim in his idle position let's put a floor in here so let's expand the sample senior right click can create the new objects let's just create a cube that we set in minus 0.5 here a floor and let's make it 20 wide maybe and we can create the new material so it's not so white let's create a new material and call it floor and then make it gray switch off some reflection okay and we can flip the cowboy around as well so he's facing the camera here before I get into the eye K I'm gonna make him move so let's make a little script here so let's create a new folder called scripts and then let's create a new script here and call it a cowboy and let's put that script on the cowboy himself there's a few things that we'll need for this guy to move we need to put rigidbody on him and we need to put a capital Collider and my character is about 1.8 meters sighs well it's making that and then put the Y position here to 0.9 so that'll put the capsule like this if I press play now you should stand and that's good and let's start some coding so there's a few things I want to set up for platform is it's usually good to gravity that is higher than the natural if you use a normal 9.81 meters squared in a platformer game it'll look like it's running in slow motion what we can do then is let's just change this here so like let's go into project settings here and let's go into physics and let's change this to minus authority so trust me you'll want to do that so unless you want a slow motion game realism is rarely good in a game make it fun instead okay so we've had our we've got our cowboy script here but a few things that we'll need is we'll do some public variables here and the first one is we'll have a float which is the walk speed let's do that initial default to two-and-a-half units per second and then we do a public jump Ike we want as well and we want the character to be able to jump maybe five units up in the air so we can make it to a different platform and I'll be using rigidbody for my platform and I know some people use just transform translation I prefer to use rigidbody and applying some velocity changes and also prefer to to have this predefined jump itís title just applying a random force I want the script to calculate which height you should be able to achieve and the script will compensate for that so we'll get to that in a minute okay there's another few things that we need and it's a reference to a transform transform that we will call ground check and that's because we need to be able to know from the script if the guy is touching the floor or not in this under the cowboy here let's create a new game object empty and let's call it ground checkered ground shake oh yeah development like this you want the center of the character's pivot point to be at the character's feet so that's where we're gonna put this ground checker and as you can see now this is exposed here so let's just drag this ground checker transform onto the ground checker there so that is done we'll come back to that in a minute with with the code we need to set a radius here so a ground check radius and let's make that zero point two units okay and we can start and then we also need some private variables so let's do a private reference here to animator which we'll be needing to send speed and stuff to the animator and we need a bool here this ground that we need to know if the character is grounded or not and in the start here let's do let's grab these components so anim four equals get component animator so in the start Ramona behavior here we set up to grab that reference and also we need the rigidbody so let's do a reference to that privates body body let's grab that one here as well our body equal skip components and the reason why I do that here in the start instead of always doing the get components because it's much faster to save the reference into a variable like this rather than using getcomponent in every frame if you care about performance don't use get component all the time just store the reference in a variable in the update loop here now we need to stop grabbing some inputs so we need another load here so we do privates movement we need to store how do we want the character to move and then here let's do input movement equals input get axis horizontal so horizontal let's keep an American since we're using a rigidbody I'm gonna do the actual movement code in the fixed update which runs on a fixed rate and by default it's at the hundred Hertz which is a hundred times per second so and that's a fixed rate and that's where you want to be doing your rigidbody changes so fixed in fixed update here that we need to do let's set the velocity now so we need to do new vector3 and let's grab this input movement and then put the x multiply that by by the walk speed and then we need to do we want to keep the y velocity which is the up-and-down we want to keep that one to what it was before and then the Z movement we don't want any movement at all no velocity in the Z because the Zed movement will be depth wise so into the scene and alter the scene we only want this character to be able to move left and right which is this movement left and right with a walk speed and then we want to keep the current Y velocity up and down so let's press play here and see what happens okay so he's moving left and right so I'm pressing right now he's obviously moving right maybe not the most graceful movement but let's fix that we can't have it like that can we here in the rigidbody let's expand constraints and then we want to freeze the position first of all we only wanted to be able to move left and right and up and down not into the scene and out so let's freeze the Z position which is this blue axis here and then for the freeze rotation we don't want to be able have him rolling over like that we don't want him to be able to rotate around the z axis which is the depth wise so that we block let's try it again now he's sliding left and right so that's good we still need to make him walk and face the right direction but we aren't on a good path here as you can see now we don't want it to rotate like this either so we can in fact freeze all rotations because we'll be taking care of this in the script okay let's make him face in the correct direction now let's go back into our script let's call this one movement so you know that one and then let's call this let's do something about that facing rotation oh and here we need to do again with the rigidbody and now we do a move rotation which is the way to tell a rigidbody how to rotate and still take into account the backend physics of unity you could just set the transform rotation but to recommend a way to do it for rigid bodies is to use the Move rotation method and for this we need to do Sarnia which is the rotation and we need to calculate the new alert and we'll create a new vector here and the X component is nine is zero and then around the y axis which is up and down we need to know 90 degrees and then we'll need to do math F and then sine sine is going to give you either minus 1 or plus 1 and we need to calculate here so we'll do let's see now I'm gonna use Mouse aim actually as well I always wanted to face in the direction where you're aiming because the whole goal of this tutorial is to make the ika mning so what I'll do here is I'm gonna put some code in that won't run just yet but I'll fix that in a second here I want to be putting something called a target transform position X which is the position of my mouse cursor in the x and y sorry in the X Direction left and right and then I want to do - this transforms position X so I know if it's to the left or right of me and then for that we want 0 and this one's red now because we're to find this so let's create here let's do we can do it so it's visible let's do public transform targets transform and it's got no reference at the moment but the code will work now so again if I press play now nothing will really happen yet since that is not being assigned yet which it hasn't we can actually create a new one here let's call this one that was created empty here target transform and for this one you could actually put the crosshair for example or a sprite or something like that I'll just keep it as a blank object for now so let's just drag this target transform to here oh I got 2 cowboy scripts sorry about that don't have two scripts there we go so as you can see now he's facing where the target transformer which is in the center of the screen I haven't implemented out Mouse aiming yet so as you can see he's gonna be facing where the target transform is and we're gonna change this we can actually change this now so it follows the mouse I'm going to do that we need to have a reference to the main camera and let's do main camera equals mean and again the reason why I don't do this in the update loop is because calling camera dot mean is quite expensive as well performance wise it'll find the camera every time in the scene so if you have a lot of objects it's unnecessary so let's just put a reference into this main camera here and then we need to do some ray casting here so in the update loop here I'm gonna create array so from the main camera we want to do its screen point to ray input Mouse position and then we want to do a ray cast hit I'll explain this in a second note and then we want to do if physics ray casts ray that we just defined out that to a hit and then math let's send this to infinity to infinity and beyond anything beyond I mean watch the was it Toy Story I mean what's that you know one and then I also want to create a mouse so let's create something called a mouse game mask here and this one's not defined yet so there's a nifty shortcut here if you press control period it'll suggest generate variable Mouse a mask that'll save you some time saves you typing it by manually so but actually I want to change this from a into a layer mask how we're going to make it public so I could have typed that anyway and if if there's raycast hits this well I'll tell you in a second as well why we need this mouse mask here but if this Ray casts hit this then we want to do targets transform.position should be equal to the hit position point and this won't work just yeah but it will work in a second what we need to do now is create a new object so I'll create an empty put this at zero zero zero in the scene and let's call this one mouse invisible mouse targets like this and then let's create a new layer here and call it Mouse target and let's assign this layer to this object here and the reason why is because now we can go into the cowboy here and I can set this mask here to just be the mouse target and for that finally we also need a box Collider and we want this one to be really wide so a thousand for example as you can see and then a thousand hi and then we need to position it at 0.5 actually let's make it small again so you can see so if you can see now that this front face is now right in the center of the screen usually you want all the bullets and everything to take place in the center of the screen or the 22.5 platform or north in the center of the deck to eyes anyway so let's keep everything at 0 in the Z position so that means that I've got to put this target Collider here so that this part of it if I'm looking from the frontier will hit that particular point so now if I make this one large again a thousand by a thousand then this Mouse target now should in theory work oh yeah here's an important point as well my character stopped being able to walk now left and right even though it was working before and that's because we've got this big massive collider here and that's why we put it on a separate layer like this because now we need to go into the project settings here and then in physics we need to disable all the collisions for the mouse target layer and now we should be able to move again because we only want to use this layer for the actual mouse position target here and now you can see that when I move the mouse he'll flip left and right depending on if I'm aiming to the right of him or if I'm flipping or if I'm aiming to the left of him so if I move here you can see that everything is working he's sliding yeah good skater let's make him walk now so we need to do the walk animation and for that I need to go back into the animator here and let's drag these in will put the walk animation in here call it forward and then we transition from the idle and back I right click here and do make transition we need to also create the parameter here and let's call a float let's call it speed because we need to transition to the walk forward if the speed I press that plus there is greater than 0.01 and then I want to transition back to idle if the speed is less than 0.01 and here's an important one as well we need to click out this has exit time because we don't necessarily care about a walk cycle finishing so let's deselect exit time and as soon as the speed drops below that threshold then issued transition immediately back to idle back and forth we haven't told the animator anything about this speed yet so let's so nothing's gonna happen if I press play now but we go back into this cowboy script and if you remember we changed the velocity here let's put the little thing here so we'll put animator will set the float and we called it speed and then we want to do it the rigid body velocity and we want to do the X velocity divided by the walk speed that'll basically give it between a value between 1 and our zero and one okay let's press play here we go okay we've got some funky stuff going on he's walking up in the sky first thing I see is that I'm not looping the position here so let's do that let's fix that the walk cycle here we need to loop time and we need to bake these in to pose like we did with the other one in the positions and rotations and we're gonna make sure that we don't have route applied the reason why he was going up in the sky is because we had apply root motion enabled so that one has to come off because we're not in this video I'm not using root motion so now we should have hopefully bit better yeah he's walking up but if I reverse he's not going anywhere well he's gone backwards but he's not walking so to keep it simple I'm just gonna reverse the animation if he walks that way so let's duplicate this one and let's just do similar here but in this case it's transition and then transition back to idle let's call this one walk we don't want any exit time on this and we need to add a condition here so if speed is less than - 0 0 1 then it should walk backwards and if it's greater then - ok ok and now and you can see that is walking this one we can see it here and then when I walk back what it's doing that one but the walk cycle is still forward and to fix that we can actually just we want to change the speed here anyway so let's do here let's multiply let's use a multiplier here speed and here when I use a multiplier speed as well so now I was walking backwards you could probably create the new walk cycle for I'm walking backwards they probably look a bit better but for simplicity now I'll just use the same one back and forth like this ok now you can see that if I flip here it's a bit incorrect because now he's doing a moonwalk and it's the opposite here so we need to take care when he's aiming left and right we need to tell the animator that we're facing a different direction and to do that we can modify this script or a bit let's create a little getter here that we can use for this let's call this one actually we can make it privates and it's an gonna mean integer called just facing sign and for this one we need to do a get and then let's do some some checking here so perpendicular vector three we need to do a cross product here of the transforms forward with worlds forward and then we can calculate the direction now so we do floats Direction equals and that's going to be the vector three dots of that perpendicular towards dot product transform up of the characters of position if this doesn't make any sense to you it's a mathematics to just calculate if it's going to be on if it's facing left or right so you can just copy rewrite this code or if you if you want to reuse it or you can look up how the math behind it works if you want and then we need to do return the actual sign value now so if Direction is greater than zero then we return minus one if it's not then we need to check if Direction is less than 0 and if it is return one and if it's need neither neither if it's not any of those let's return 0 so this will check if direction this direction here is greater than 0 well then we know that this sign is a minus so minus 1 where your time if not we check if it's less than 0 then we know it's going to be facing the other direction which is returning the sign 1 and this condition shouldn't really happen the 0 because it's going to be an arrow we don't really want to ever have a 0 that's gonna be we have to check that once a month nevermind and this is just a short time for if statements instead of nesting a bunch of if statements basically this is a shorthand to write if statements so it just returns the value ok and we need to use this one down here now so facing sign and let's encapsulate this with some brackets to make sure and now the character should take into consideration so here the walk cycle now works and the animation is correct because we calculated if it's facing left or right now there's a lot of talking for a little piece of code okay let's implement jumping as well we need that first of all let's go in here and let's grab the input here let's check if get button down jump then we do rigid bodies velocity equals a new vector3 rigid bodies velocity X we want to keep that one and here we're actually going to reset the velocity node so we're keeping the X velocity of his movement left and right but we're gonna reset the Y because we're gonna set a new one and that one we need to add a force you know so let's do rigidbody add force and we want to do vector three up because usually you want to jump upwards so let's do a jump and then we'll do some nifty calculations so let's do the square root of the jump height times okay gravity yeah physics dot gravity we need to take into account and take into account and then for this one we also need forest mode velocity change okay we've got an arrow here not saying I can't come oh yeah it's because we want the Y component of gravity right at first of all we want it to be negative with that piece of code now he can start jumping but he walks in the air so we don't want to be able to do that and if you remember before we created a little thing called is grounded here so let's start using that one we can just simply add here if get much button-down and if it's grounded is not true then he will jump that won't work straight away we need to also calculate now if is grounded is set or not and for that we can add a little ground checker let's put down here in the fixed updates check its grounded physics and then there's something called check sphere which overlaps a sphere into a position and then ground check transform position ground check radius and then let's add a mask as well so let's do this I'll add that in a second or query trigger interaction we want to ignore any triggers for this one let's press control period here on the keyboard and generate this one and for the ground mask actually we want to make this one public and we want to change it to a layer mask let's move it up here or tidiness and now like we did before similar let's create a new let's see let's create a new layer here called ground um let's assign this one to the ground layer this floor one and then we also need to go back to the cowboy here and then set the ground mask to ground so you can add more in that layer mask you cannot if you should be able to walk on other things than the ground like other objects or things like that put them in the same layer mask here so this is the layer mask that you changed them okay and now you can't jump and can never jump down so let's check why the ice obviously he can jump if he is grounded not if he's not if he isn't grounded so let's fix that so if input get button down jump and the character is grounded then he can jump there we go so now I can't he can't jump in the air like double jump now but he's still walking in the air I'm walking in there you seen that film with the Snowman should check that out quite nice it's night for Christmas if you haven't seen it so we need to fix this now so with the jump here we did this is grounded we also need to tell the animator this so let's do animator set rule let's call this one is grounded it's grounded and I'd set it to the is grounded liable here and we also need to go into the animator and add this one which is going to be blue I'm just going to be called is grounded and then we need to change that condition here that it can only transition into this here if it's grounded it's true same for the backwards it can only go here if it's grounded it's true and then here from any state let's make a transition to idle if it's grounded this false that'll basically force him into the idle state if he's in the air so I won't be doing any more details for this one but what you ideally should do instead of using the idle state you should really have a crossfading falling animation so that he'll basically raise his arms as he falls faster and faster I'll put a little screenshot here or a little video clip up in the corner so you can see how it looks in my game when I do it but for for the purpose of this tutorial by doing that I can do a separate tutorial on the jumping mechanic if you want to have this blend tree of the falling animation so give me a shout in the comment if you want to see that in another video he's aiming left and rights he's walking left and rights and when he walks past the aiming point he'll flip and start working backwards whether you want it like that it's up to you maybe you want to walk maybe you don't want that but since I'm gonna be using miles aiming that's the whole purpose of this demo so that's what I'm gonna have him flipped left and right okay we've finally got to there aiming the I can out so we need to use some let's create a new layer here and call it upper body so we're gonna create an avatar mask so let's create a new folder and call it a Vitara musk let's create a new avatar mask and call it cowboy musk and for this one we want to disable the right arm in the head because we want to use I for for controlling the arm and the head movements towards the target and for the base layer let's do i cape us and then put this cowboy mask there and since we've got Ike a pass on the animator now there's going to be a new model behavior that's getting cold and that's called a row on animator Ike a and we don't really need the layer at index here so we can take down all the way and then here let's do the weapon aim at target okay and here we do animator set by K position wait avatar iCade goal dot and we want to use the right hand for this weapon and let's set this weight to one which is full full weights we want to have all the I key that we can get and then animator we do set a key position avatar I go right hand we want to use again and this time remember that target transforms and let's grab the position for that one so now if you press play he's moving his aiming left and right he's not so happy with the with the ground he's in the floor so we need to fix that and that is because we need to set these so weight is one and this one needs to be weight one as well so we need full weight on both and this one is set to override for blending so now he's working so now we've got the hand moving so at this target transform you can see this one is actually moving here as I move it it's an invisible object so you can't really see it but there's an object here and we can prove that by let's put a little object here 3d object sphere here a tiny one and if you can see now you can see that that little sphere is let's make it a bit bigger so you can see here now you can actually see where he's aiming so this little ball here let's take away the sphere Collider we don't really want it to collide here so you could have a crosshair there for example a sprite with a crosshair if you don't have that and then you can hide that there's a way to hide the cursor that default windows one so you can use that one if you just want to cross here instead or we could hide it all completely we also want him to look here it'd be quite skillful if you just shot like that well let's make him look at the target as well so for this one in the same on animator ika here we can do so let's call this one look at the targets okay and then same we need the animator and then set set look at weights will step out onto one so full and then animator set look at position again we wanted to look at the target transforms position that's what we really need and now he's also looking in the same ways aiming the I K is only affecting now according to the layer mask there and the IQ pass it's only and we're only using I care now inverse kinematics for their hand position and aiming and also the look at target so the head here and when he aims up in the sky here he'll flip over and start aiming down here so this is gonna be quite a long video I guess but let's finish off as well with him and being able to shoot some bullets and also have some recoil and and that we have to do procedurally because we want to have the recoil calculated after the AI K is applied then we want to do the recoil so you can't really use a normal animation for that that you've modeled in blender for example so we'll do that here so first of all again look in the description if you want to skip forward straight to the recoil bit but I'll have him shoot the bullet first so let's just create a very basic bullet here let's create a new game object called bullets let's create a script here called bullets as well now we assign on to this one oh it's a quarter past three in the morning I should get to bed soon okay and let's add a component here and we want a trail render and that's add also a little bullets wheel let's just do a sphere for now really tiny 1 0.05 then we need to create a material here called trail from bullets trail let's do a particle unlit and not to make this one great and let's make it here we go and for the bullet here we know wanna disable shadows shouldn't cast or receive shadows and then for the trailer end or if I do not that one did I not know Trail Ranger we want to have the initial path is quite small like so and then and size should be zero we don't want oh yeah we can fade it to alpha zero and black it's additive so it's the black that's important not to color everything else here is fine we don't want to do shadows it's unnecessary for that one but we do want to assign the bullet trail material there so this by itself won't really do much we also need to be able to make the bullet move here and for that we need to set up a few variables again so public float velocity maybe 20 probably life is gonna be one second the bullets loop and then we have to take into account which layer fired it because we don't want the bullets to collide with yourself necessarily when you shoot it and then we also need to have a float with a life time primer so we can keep track of when it was fired and let's create the public method here called fire and we want to grab a vector3 position where it was fired and vector3 healer angle and a layer that was fired from and then the life timer life timer we want to set the time about time so basically that's a timestamp the transform position we set to the position that was supplied so and the Euler angles set to the Euler's that we supplied and the position and the reason why I do this is because I want to reset the position so we want to have the Z component to 0 because we want the bullet to always be fired in the center remember we have just no depth basically and enemies are going to be hit we don't want bullets flying next to objects either to the left or right so let's force the Zen components is zero that's why I force that here when the bullet is spawned also I'm gonna instantiate these bullets and normally use a pool instead I'll create another tutorial on that as well object pooling but it would be way too big to go through pooling in this video so I'll leave that out for now but that's why this is a little bit prep for for a pooling objects so there's a slight bit of extra code here possibly we need to calculate our variable layer as well which is a projection on the plane projects on plane and then the objects transform forward with vector three forward and the transforms forward now it needs to be the projected one and then finally we need to do the look rotation for the bullets to the projected one with forward I won't go through this code in detail it'll take some time to explain but basically it's a way to make sure that the bullets are gonna be flying in in the zero position and they're gonna face in the right direction based on the aiming I K we're going to submit in which direction the bullet should fly and this is a bit of piece of code that helps that calculation take place so I won't have time to go through it but if you copy and write this one it should hopefully work okay and in the update loop we need to do make sure if the bullet hits something so and to do that we did need to do a ray cast so we do ray casts hit and if ray casts sort of transform.position to fans and adduction is transferred the bullets forward direction we're going to out that into the hits variable and then when I do calculate how far we're gonna check and it's gonna be velocity times time delta x or how long the bullet travels in one frame and then we want to do a layer checking here to make sure that the layer is not the fired by layer which i've also misspelt and this is to prevent the bullet from hitting the gun that it was fired from that's why I do this layer mask here and then we do transform position equals hits position because when the bullet impacts if we calculate here the bullets can fly really fast so the raycast will make sure that it doesn't go through the object it'll check where the next frames position is gonna be and it'll do a ray cast and if it hits the object within that period of time then it's gonna trigger a hit but we need to move that bullet so it doesn't create an explosion or whatever impact effect you might have in a head of the object so that's why I'm forcing the position out to the hit point that's the whole purpose of this piece of code there and then we can do some calculations here as well that might be useful for you and that's the reflected vector vector three reflects that objects transform forward with a hits normal and that's for work and this one I won't be using in this demo but it's really useful to have this one if you want to have sparks if you have an object a bullet that hits a wall and you want sparks to fly like a ricochet type of thing then you can use this reflected this is the direction of that reflection we also calculate the direction which is the transforms forward and then we do another projection on plane here vector three vector three projects on plane and then selected this time and then we do transform forward equals detective forward transform rotation so this is the same old similar to the code that I had before when I did my platforming game I had some issues with when I forced the bullets to fly in a certain direction and getting the reflection and everything correct that's why I found out where I introduced this piece of code and that'll help the bullets to fly in the direction that you want them to and hit and calculate all the reflections and things like that if you don't understand this fully out don't worry about it it takes your add a bit of getting used to and I could be honest I can't hardly remember it myself how how I came up with this but it it works for my purpose probably the worst comments ever in a tutorial I think okay and that's to let's create a method called hits and then let's do a transform position and submit the direction reflected with its Collider as well general method control period I press there that will automatically generate this method and here basically what you can do here is do something here with the object that was hit and you can access that one with the collider so if you use for example given coli their dot game object and then you can either destroy it for example using this reference here I won't be using that in this demo here or in this tutorial all the things the only thing that we're gonna do now is destroy the bullet itself so destroy this game object hit something oh yeah we also need to make that bullet expire and we also need to translate the bullets so here if if there wasn't a hit then we need to translate the bullet forward so let's put else here and then the transform translates and then we do it in the vector three forward direction times the velocity of the bullets times time dot delta time because now we're not using a rigidbody we're doing it every frame we need to multiply it by time.deltatime to make it framerate independent and then finally we need to do a check here as well okay and we're back ran out of battery and a memory card so let's continue sorry about that not that you noticed anything it just went like that first I guess ok the last thing we needed to do here is to expire this object so if the time is greater than timestamp life timer plus life was life then we destroy this game object as well okay objects there we go a lot of code for this bullet here but now it's finished finally the bullets itself is finished but we also need to fire the bullets so let's go back into cowboy and here in the update loop here we need to do if input you get button bound fire one which is like left mouse button we call a method called fire and then we generate this one first of all let's instantiate the bullets so we'll create the reference to a game object and we instantiate something called the bullets prefab we need to generate control period here and then generate no we don't want to control periods and generate a field which will be object instead and then we actually need to create this into a prefab so the bullet that we have here let's drag this one here called prefabs and you folder and then drag this one into there to create a prefab we can delete it from the scene and on cowboy here now we have we should have a bulletproof up here no we don't yet oh yeah it needs to be public so you can see it in the inspector oh yeah we were meant to try that on today it's time to make mistakes now even though it's only 351 a.m. I'm still doing mistakes I wonder bye cowboy let's bring this bullet home so in the prefabs folder here now we can find the bullets and then do that one so now we'll instantiate the bullet when we press fire but we also need to do some more with this bullets we need to set the position for it and then here we're actually going to create something called a muzzle transform and similar to what we did here let's do public transform muzzle transform because we want to know where the muzzle of the gun is that revolver here so if I go back to here now we can expand this I hold the Alt key and click here so I expand the whole hierarchy and then we find the gun here and we create a new object create empty and I call it the muzzle we double click on this one to find it in the scene and then we need to just move this to the tip here of the pistol this is where the bullet is gonna come from and it's important that this blue arrow here the X the z axis is pointing in the same direction as the gun itself and when we've got that sorted we need to drag this muzzle onto the muzzle transform it's not appearing yet it's because we've got an error and we need this one's position and not the object itself and now it should appear here there so let's drag this one on to there so now we can actually position the bullet at the tip of their pistols barrel and then we need to grab the reference here to the script that we created so the game object will have the prefab that we instantiate that will have this component on it that we created which is the script and then we also need to call this so bullet fire and then we set the transom the position will be the transforms position of the bullet itself since I've already said it and then the direction will be the Euler angles of the muzzle that we created and then the game object layer is the layer of the player itself so that should be it and now the guy should be shooting some bullets here hopefully ok we've got some issues with a trail render oh yeah I think did I add to trail renders by mistake oh it's because it's on the sphere huh ok so my bad No well it's way too long the trailer ender so let's do the 0.05 it's still a bit too big so let's make it smaller and whether you want a trailer or not that's fine as well but now he's shooting in the direction so the final thing the final final final thing the final countdown the final thing final fed up with myself okay so the final thing we were gonna do now is just doing the recoil of the gun or the pistol itself so finally that's not actually much of a code so in the cowboy script here we need a few more variables to set up so here in the public section we'll do public and let's create an animation curve call it recoil curve then we need to create the duration of the recoil so recoil duration equals maybe is 0.25 seconds and then we need to calculate or say the max rotation of the recoil I'm gonna just do recoil with that lower arm now so when he shoots it's gonna recoil the lower arm you could go full monty and do recoil with the shoulders and the hands and everything like that but it'll follow the same principle so I'll just do the recoil now with with just the lower arm so you know and for that one will do recoil max rotation equals 45 degrees and then we need to do some reference here as well public right lower arm we need boats and also the hand right um and then we need to actually assign these here so if we have our object here the cowboy we need to grab these references so right lower arm is this one in the armature and the hand is this one okay we've got those and now we need to create a little bit of code here as well and it's going to be on this fire one before we fire the bullets let's set the recoil timer to time double time and we haven't actually created that one yet so control period on the keyboard and generate field and that's a float which is fine and here when we fire now we set the timer here the recall timer to time and then we finally need to add this one as well which is add the mana behavior which is late update and here I need to do some coding so it'll be recoil animation comes here so if the recoil timer is less than zero we don't have to do anything here so we will just return then I'll exit this late update loop we don't need to do it it's important to do this in late update as well because the inverse kinematics will always aim in the direction but we add the animation in the late update which runs after the I K is applied so we can modify the position here so we need to calculate since the recoil timer is running that we set in here in the fire method then we know that recoil should be animated so let's calculate here the current time which is going to be the time duck time - recoil timers timestamp and then divide that by the recoil duration then we're going to get a value between zero and one of the duration so when it's zero it'll be zero when it's 0.25 which is the current duration of the recoil it's gonna be this value is going to be set to 1 and that's because we want to evaluate here so if if curve time is greater than 1 then we know we're finished with animation so then we can just set the reset the recoil timer to minus one so it won't run anymore but if it isn't greater than one that means that equals that means that we should animate the recoil so here we do the right forearm sorry the right lower arm and we rotate this around vector3 forward and here we evaluate the recoil curve with a curved time which is between zero and one remember we need to multiply this by the recoil max rotation so 45 degrees at the moment and then we need to rotate around its itself so it's going to rotate around its own axis then what we need to do now is actually set the animation curve itself and that's you can configure that on how you want but for example I think I've already you just click on a default preset here move it down to zero it should start and end at zero you can right click on these and edit the key to make sure that it is zero yeah that's good and then we just create the bump here and double click there and create a bump here and then a slower return so you can draw this curve as as you wish for the recoil now basically I'll go up fast like this one and it will slowly lower the pistol as well after the recoil so maybe something like this let's try it out there we go so you can modify that curve as you wish for the recoil if you want it more if you want to increase the recoil you could go all the way up to let's say 90 degrees if you want a big and you could also change the speed for example here of the recoil to one second for a really slow one so okay let's keep it up 0.25 and 45 I think that was pretty good and then we can duplicate the control D here to duplicate this objects and then just make sure that you can jump up here as well let's make it a bit smaller temp let's make sure you can jump up on this platform okay here you see that he sticks on to the side and I'm glad I did this one because you don't want to fall for that one let's create a new material here a physics material and let's set the friction combined to minimum and then zero friction ooh and then for the cowboy here here on the collider put the physics material that we created here onto that this capsule Collider and let's call it zero and now if you want it won't slide and we can make the capsule radius a bit smaller as well because it was bumping a bit too so 25 like this okay and you can't jump up to that platform let's do ten okay just increase well let's move the camera up a little bit like this and then what I'll do as well is if you look at my channel history there's a little four pixel sky tutorial that I made you can check up in the corner maybe I'll be able to put the link up here as well so otherwise it will be in the description as well so what I'll do is I'll just drag in an asset for that but what you can do is follow that tutorial it's called for pixel sky or something like that and then basically it's to go through to create this texture called four pixels sky and this material called for four pixel sky and then drag this one to their own little texture then we can just create a new object here in the scene and let's make a quad let's position it back here let's disable shadows and then make it really big thousand wide and maybe 200 high and then assign the 4 pixel sky texture to this object there you go and then we can make it maybe 50 40 okay it's just a bit of a nicer sky for platformers like that so I think here let's see let's maximize this and play a little bit so we've got our guy walking back in backwards got our guy walking forward and back left right we can shoot bullets the bullets die as we hit something with Ray casting and we've got the recoil and we've got the aiming set as we did it'll point in the direction and you look in the right direction and shoot all right so roof okay that turned out a little bit longer than planned for Oh 6:00 a.m. in the morning here for me but I hope I didn't forget anything now all right so everyone that was a bit of a long video but we got to do it in the end hopefully you didn't fall asleep and hopefully it did give you some help on how to do the inverse kinematic or the I K aiming with the straight out of the box I Ketu 'ls that you have with unity so it's really straightforward to get that hand pointing in the same direction as your weapon and also having the head tilt up and down it's pretty much prep for that one to begin with so this is set up for just a single handed weapon and you could either modify it yourself to accommodate the second hand if you want to have a rifle or something like that or again put it in the comments if you want me to modify this one and do 200 weapons as well I guess that's gonna be a follow-up question fairly first don't forget to hit the like button if you like this video it'll help me out a lot and subscribe if you haven't already I'd love to be able to add some more videos for you to watch keep making games I hope you get really far into this have fun with unity make games and until next time have a very good day I'm a very good data good [Music]
Info
Channel: Imphenzia
Views: 49,880
Rating: undefined out of 5
Keywords: mouse aim, mouse aiming, ik aim, inverse kinematics, platform game, mouse target, target with mouse, aim at mouse, look and aim at mouse, tutorial, imphenzia, unity mouse aiming, unity weapon aim, aim weapon at target, aiming a weapon at target
Id: zjoHEKHRDeY
Channel Id: undefined
Length: 66min 26sec (3986 seconds)
Published: Mon Jan 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.