Say thanks by Wishlisting my game Blood And Mead on Steam!:

In this game dev tutorial; you will learn how to create a 2D player controller in Unity using C#.
I will be covering the following:
– Project setup,
– Sprite sheet and animation setup
– Keyboard input mapping
– switching between animations
– line casting for collision

Subscribe here for more cool tutes

Graphic assets for tutorial:
www.johnstejskal.com/simple2dController_assets.zip

Join the community! (help and game dev chat):

#gamedev #unity #lostrelicgames

what's up guys welcome back to another tutorial today we'll be making a very simple play controller for 3d games in units before we get started my name is John stay skull I've been making games for over ten years now I'm currently working on a Viking adventure platformer called blood and Mead so hit the subscribe button down below and make sure you hit the Bell notification to to get a heads up for any new content okay let's get going so let's get started by opening unity making sure our unity version is up to date and here we'll create a new project let's call this simple player controller 2d player controller and from the template drop-down make sure we've got two DS selected that will give us all the presets and orthographic camera and out-of-the-box tooling that complements our 2d workflow all right now that unity is open we can see over here we've got a main camera and that's it so first thing we're going to want to do is click over here in our project tab and we see we've got two assets folder so what we'll want to do for step one is to create a couple more folders that we can use so right click in the assets folder and create a new folder and we'll call the first one graphics now here in there we'll put all our sprite sheets and backgrounds and all that stuff create another one and call this one animations so I've got a few pre-made sprites here that I'll be using we've got like a megaman sprite sheet a platform and a background so what I'll do I will grab all these three and drag them into the graphics folder we created so let's close that off and we'll find now that in our graphics folder we've got background platform and player so for step two we'll be creating our first animation click on the player object over here and here we get all the information on the on this graphic you can see that the sprite mode is set to a single in this case we want it to be multiple as we'll be using different frames and click on sprite editor apply that so in the sprite editor here we get to slice up our animation in a way that we can use so over here leave that as automatic you change the pivot to bottom which would kind of put it in the middle bottom and let's hit the slice and see what happens all right so we can see now that unity has sliced up around the bounds of the graphics so that's kind of cool so what we'll want to do here you can also see that immunity has named it in a bit of a funny way just a 1 2 3 4 5 6 kind of situations so let's hold the sprites by their correct name so call this one idle one play out idle – this one is jump it's a single frame and then we've got three run animations here so play our whoops play our run one and run three so we've got a bunch of our bound animations that we're not going to be using in this tutorial so let's just select some of these extra ones and delete them just to make the project a bit simpler I'll probably make another tutorial later on dealing with the shooting and stuff like that and let's hit the apply button in the top right over here close it off if we hit this drop down on our player object we can see the different animation frames that we created so now we'll start by creating our first animation and in this case we're going to be making the idle animation there's a few different ways to create animations unity my personal favorite is to select the different frames holding shift that we want to use and drag them straight into the scene view and this will prompt us to create a new animation so we'll navigate up to the animations folder we created and call this one player idle save that okay so now we've got a player in a scene and we'll notice down here in the preview that the sprite is very small and click the main camera and we'll just want to go over here and change the size bit so we're better in frame you can also drag the the bounds of the camera here so we'll try to get that well like that so we'll just click play on this and see what happens okay so we see down here Mega Man's going into a epileptic blinking frenzy so we'll close that off so what we need to do here is actually address the frame rate of the animation because by default unity sets it to 12 frames a second without player selected let's click the animation tab down here and you can see here the player idle animation has 12 frames a second frame rate and here are the two different frames that's frame 1 and frame 2 so we'll want to we can actually preview animations here so we can see what's going on here it's just looping very very quickly through that animation so if we change that to say 4 in see it's got a much slower cycle so what we might want to do is drag this across there so select his first frame ctrl C for copy and bring it over here and control V paste so now we've got him opening and closing his eyes and what we'll do we'll just bump this over and we'll paste another copy of that frame over there so now if you look if we expand this out we can see the whole playhead will click play and we see what's going on now in the preview is opening and closing his eyes and it's like a delay so we can extend that delay out even further by dragging it on there that looks pretty good that's not too far off what the original Mega Man behaved like we've now actually created the player object already by making this animation so we can see here it's by default to call the player idle which is the name of the first frame of the animation so let's click that in rename to player and you can see a few different things attached to it the sprite renderer and animator so you may notice that Mega Man is looking a little bit out of factored in terms of the graphic fidelity being pixel art we want this to be really sharp what we'll want to do is go back to our animation component over here from the filter mode down here which is currently set to bilinear we want to change that to point so point is what we'll use for pixel art and bilinear and trilinear are useful for like vector art or any other non pixel art formats click and wow look at that automatically that just went super crisp it's magic so that's perfect so let's now create our run animation which will follow the same process shift select frames one two and three drag them into the view navigate up to our animations folder and this time we'll call it save that and if we just preview I see now we should get both animations playing here at the same time or megaman clone okay so what that's actually done behind the scenes is created the animation so we don't actually need this game object in the scene view anymore we can delete that one because because we'll be actually using this one here and then attaching that animation to this one so we can do that quite simply by selecting our player going up to the animator tab over here and we can see here we've got the player idle so this is a unity it's making him feature which is used for creating and managing transitions between animations and things like that it can get pretty complicated and it's kind of beyond the scope of this tutorial so we'll just use it in the bare minimum way so we'll go to our animations folder over here and grab the run animation which is identified by this little box with an arrow not to be mistaken with the one underneath it which is the animation controller which gets automatically generated when we create an animation so grab the player run and drag that into here so look at the idle and the run and here you can actually set the default player animation by right-clicking and set as default so when you do that it basically says make the player run straight away or make the player idle straight away which is what we want in this case so going back to our scene view we'll want to click our player go to the animation tab and what we'll notice here is now that here we have the run animation so if we select that we can preview the run animation and that looks actually pretty good I don't mind that I might just try lowering the frame rate to ten in this case and see how that looks let's try eight what do you guys think kind of eight nine ten I think anywhere but let's stick with this kind of sweet spot of nine looks alright so the final animation we're going to be making is the jump which is a unique case because it's a single frame so what we'll want to do is navigate to our graphics folder select the jump and see what happens when we drag that in you'll notice that we don't get the same automatic prompt to create an animation because it's only one frame it's like it's not an animation what do you do but here we do get this option here to create it so let's click that and we end up within the same options so navigate up and is this one will be called player jump start save that okay so and once again we'll delete this one click back to our player we need to add the jump to the animator so let's go over to the animator here click on your animations folder find it the jump animation and bring that in here and you can kind of organize this however you want these windows can get pretty complex if you can imagine some games have you know over 30 animation states depending on what kind of game it is go back to the scene view the player selected will notice now we have a jump it's creative and empty animation which is kind of what happens when you try to create a single frame animations but it's an easy way to fix this with this window open click on our graphics screen folder find the jumped frame and drag that in here and look at that we have the one frame animation and just going to be looping over itself which is fine which is exactly what we want here and in this case the frame rate it doesn't matter so unit is given it a 60 FPS as default cool so at this point we'll added the background components to kind of jazz up the scene a bit and get us on the path to floor collision and movement so go back to your graphics folder you've got your background here just make sure that's set to a point floor is at point and we'll drag the background into the scene drag the floor into the scene and will notice that the kind of proportions are a bit off at the moment terms of the background scale with Mega Man I mean ideally you want things to be scaled correctly before they come into unity if you can macro you can play with it in Photoshop or whatever but here I might just kind of tweak these things Mega Man's looking a bit big at the moment so rather they're scaling him down I might scale the background up so grabbing the background and floor holding shift I might just bump up the scale in the properties inspector over here at 1.5 that looks a bit better but what I want to do is maybe you rescale the camera a bit too so clicking main camera can grab a scale tool or one of these ones and grab the handles here might see what happens when we like that alright well we'll go with that I mean depending on the Asus you're using you're going to want to kind of tweak the camera position and the camera size so that your graphics fill the screen properly but I think that's looking pretty okay so at this point we'll add a we'll add a box Collider so select the player down here we'll click Add component I think box you should automatically get some auto-completed results and what we'll want to add is a box Collider 2d and this is the box that will be used for collisions with the rest of the world and you can see unity has automatically used the the sprites boundaries to set the size with the box Collider but you can see here that the box Collider is a bit lower than the feet so I might want to move that up a bit so over here on the Box Collider settings you can actually edit the collider so if you press that that'll toggle and the collider is now in edit mode so what you can do here you can grab the handles here and you can kind of change the Collider manually so that's really cool so once we're done with that we're just kind of on table now we're going to want to add a rigidbody and the rigidbody is a physical component that we adding to the player to say now I want you to obey the physical laws of the Unity world so over here we'll type rigidbody and we'll want rigidbody 2d so that adds now all these physical settings to the player gravity scale mass weight how heavy the player should feel in the world and stuff like that so we're kind of leave that as is and see what happens Wow okay so Megaman took a dive so now we need to add a floor to give you something to stand on so let's select our floor game object and add a box Collider component enter now so now you can see that the floor itself has a box Collider ball so if you kind of put your sky in the air run that again boom okay and you might notice there was a little bit of kind of overlap with a floor when we dropped it if you just kind of watch this again yeah he kind of goes through the box Collider and comes back you need to kind of adjust the physics settings a little bit so what we might do click on the player and here will change the collision mode to continuous so that takes a little bit more resources but it just gives us more accurate collisions so let's have a look what happens now okay so that's perfect so that lands right flush on just position Mega Man down here so what we'll need at this point is create a c-sharp script so clicking on the player will go down here add component and this time we'll select new script and we'll call the script player controller trudi create an ADD and that should add it directly to the player time to code my friends time to code so now if you double-click down here you should open visual studio and we want to start by feedback yeah so we want to start by creating three different properties that were going to be referencing first one is the animator which will be used to switch between animations then we all need the reference to the rigidbody so rigidbody 2d and call that RB Budi and finally the sprite renderer which we'll use to kind of maybe flip the player as we turn left and right call that sprite renderer down here we want to map those properties to the components so animator equals getcomponent animator okay geez rigidbody 2d because getcomponent rigidbody 2d using Visual Studio is very awesome autocomplete system sorry guys I can't type today sprite renderer equals get component sprite renderer alright so now what we'll want to do is map the keyboard buttons to move the player so what we might do we might map the a and D keys for moving left and right but also maybe the left and right arrows in another tutorial I might talk about like Xbox controllers and stuff but for now we just use the keyboard so this can be done in the update loop which is the unities game loop but because we're using physics what we'll do is create a fix to update and this is similar to the update function above but it's got a fixed time step and a bit more accurate for games that are based in the physics world which this one is so might actually just deleted the update function and in here we'll say if input dot get key and in here we'll say D or input dot get key right my auto-completion skills are not working today then rigidbody2d dot velocity equals new vector2 and here we'll give it a velocity so let's try to for the X and maybe zero the Y else if input don't get key this time we'll save a or input dot get here left parenthesis so now we'll say rigidbody2d dot velocity equals new vector to this time we'll say -2 and 0 okay so let's see what happens now when we run the scene see if I press whoa cool it's like ice skating you ha very nice [Applause] teleport out so that's cool we've got movement yeah it's not quite a game but it's always nice to see some movement on screen now we'll map the space bar for the jump so see if input dot get key space and now we'll say rigidbody 2d dot velocity because new vector2 so we don't want to interfere with the horizontal movement of the player so we'll keep it mapped to whatever it already is so I'll say rigidbody 2d dot velocity dot X so we're not changing that instead we want to change the Y so for the jump we'll say all right let's just save let's say three so now let's press the spacebar Wow okay we have a jump so now we can oh whoa what's going on this is the cool part of starting a new project we can kind of tweak things around and quite often and come up with a whole new game idea some emergent games like this could it be some kind of a I don't know floaty game some kind of bird or dragon floating down and collecting stuff and yeah so we got a few issues here we'll want to make sure that our horizontal movement is not interfering with our vertical velocity so I'll say rigidbody 2d dot velocity but why so we we're not overriding what's already happening vertically if that makes sense for the left and right movement specifically okay so we're not getting that kind of floating movement we're getting before so getting a little bit closer to a reasonable result what we might do now is change the animation so it looks kind of cool as we demoing it so what we'll do we'll reference the animator we created and in a four and we'll say dot play and here we'll put the name of the animations we created earlier so we had like player underscore idle player John play run so here we'll say if the player is pressing rice or the D key then play play play up run so we just copy and paste that down here and we'll do the same for the left and for the jump we'll say jump and also here with another else condition so if the play is pressing left or right then play a run else revert back to the idle State Wow yeah yeah some few crazy things happening it's moonwalking though that's kind of cool okay so let's fix up all that stuff so the first thing we'll want to do is flip the player he's going a left so say sprite renderer dot flip X is true if so if you click pressing the left flip it and if it's pressing a right then don't so let's preview that okay so that's working about the players got a lot of kind of slide momentum and there's no real resistance on the floor which is likely to do with the players weight so at all actually I know what it is I know I know okay so if the player is moving left or right we're bumping the velocity so let's say if he's not if he's not moving left or right and let's change the velocity to zero how's that sound okay cool so look at that now we can run and stop on the dime perfect so that jump is still got issues which we're going to look at now that one's a bit more complicated to solve so I thought it'd be nice to kind of give this running action happening and Mega Man is the best I got to say Mega Man 3 was easily my favorite one so if we click on floor and we go to the property inspector over here we'll see that delay is by default set to well to default so what we want to do is add a layer and here we'll call the layer ground and select our floor again and from here choose the ground layer we just created we'll have to now shoot like a what we call a line cast from the player down towards the floor this is a very typical technique used in unity in games and you'll see it quite often regardless of it being physics or not just a very efficient way to determine if the player is on the floor so click on our player again and what we're going to do is this time we're going to right click and create empty and what that'll do is create a game object with the in our player so what here we'll we'll name this ground check and if you click over here in the inspector you can give it a a graphical icon which you can change the size of it with the kids in the gizmo drop down over here so we'll make it about that big so what this will be used to do we're gonna shoot a line cast which is kind of a bit like a ray cast but a bit more of a simplified version down from this point here and we're going to shoot it down and look for the floor and if it finds the floor we're going to say that the players grounded and if it's not that he must be jumping so back now a script window will want to do a few things first we'll create a boolean called is grounded create a new transform call it ground check and what we'll do we're gonna serialize this field and what this all this means is that we're gonna make it available in the unity editor so if we go back to unit here and we click on our player go down to the player script you can see now that ground check is exposed over here because we use that serialized field meta tag so what we're gonna do here is well we can do two things here we want to basically we want to map this ground check object we created on the player and bring it down here so you can do this one or two ways you can click this little knob here and find the ground check here select there alternatively you can grab it from the scene hierarchy here and drag it all the way across and stranger there so that's up to you you need to gives you a few different ways to do it which is kind of cool so take your pick so in this next step we're going to create the line cast so what we'll do we'll go to this our fixed update method and type if physics 2d dot line cast and we'll say transform dot position which is the players transform and the second parameter will do the ground check object dot position and here we I'm gonna do like a mask layer thing named to layout don't get too caught up in how that works basically saying if the line cast goes from the player to the ground object in that trajectory and he hits a layer called ground then to return true so we'll say is grounded equals true else is grounded equals false which now allows us to manage the jump a bit differently so in the jump we only want it to be able to jump if the play is on the floor so at another one have a conditional in here say if ki is space and is grounded is true then jump so let's go back to our game and see what happens cool so now as you can see if you if you spam the keyboard spacebar we can't fly off in a sky anymore so that's playing a lot better the jump animation is a bit funky at the moment still we can kind of sort that out now so what we'll do here is before the animations switch to run we'll just make sure that the player is actually on the ground is grounded then allow the player to run just copy and paste back over here and same with it with the idle will say if is grounded in idle so I'm hoping this will fix the jumping animation issue so run the scene fingers crossed whoa yeah how awesome is that man that my friends is a game well not really a lot of fun so we got to change the physics properties a little bit it's a bit out of control at the moment just in terms of the speed so we might close that off and change the velocity that we were using for the horizontal movement to about one what will do it will do a bit of best practices and actually make a property for this and we'll call it run speed if you highlight the property and tap hold control attack the period or full stop you can now generate properties from here which is a really nice way to automate that process so here we'll map that one see how that goes we'll bring that over down to here – I will call that leave the – there save that it's probably about right but so two things I wouldn't mind if you jumped a bit higher and maybe you ran just a little bit faster so let's jump back and change the run speed to let's say 1.5 and we'll put it next to it gets a float and maybe we'll do the same make property for the jump speed so maybe we'll try about five and what you can do also you can serialize these as well which is kind of useful since you might want to tweak these a fair amount and it makes it a bit easier to have them available in the inspector so if we scroll down here you can see the run speed and jump speed is set here and we can kind of do it for here manually it's a bit easier so we'll change that to 10.5 change that to four I think is a good number let's make the jump five still not jumping as high as I want let's go crate let's go be crazy here and say ten just to see what happens aha I didn't map of course silly John I need to go down to the to the jump and say jumper speed okay so let's try that again this is meconium appétit oh yeah as expected the Buddha shot to the moon just kind of cool which is almost that teleport effect that you find after they let end of a level in the original Mega Man's so let's go actually we'll do it into the prop inspector let's go down here change the jump to five yep that's crazy four yeah that's that's a lot more natural I like that that's really cool that feels really responsive than it being a big fan of the original Mega Man this kind of it feels good it feels it feels great it feels a lot like how I'd expect the original Mega Man to feel I mean I could be way off by just in terms of what feels right and the weight and everything it feels good so what I think might do now just to make it a bit more interesting and more like a game I'll bring a platformer into it so in the graphics folder there should be a platform yep so bring that here and much like with the floor we'll add a box flyer to it and this automatically should allow us to jump and walk on it oh my goodness what the devil that's kind of cool I kind of want to try that again just for fun so what happened here so I've got a feeling yeah yeah just as I thought cool so we need to lock the player's rotation so click on the player and go under the constraints drop down and freeze rotation so this will stop us from spinning around so you guys want to guess what the problem is here why is that happening why is that not returning to the idle state you may have guessed right we need to make the platform part of the ground layer so select the platform and from down here select around okay cool see that how cool is that yeah woohoo this is awesome Oh got some issues getting stuck here which is not and obviously we can't go through the platform but let's try to change that so what we can do here is use a one-way platform so let's see if I remember how to do this so we need to make a platform effector I think okay that's it sorry my brain is just sticking over there it's a lot to remember often in these things so in the Box Collider component we want to toggle the used by effector just to let it know it's going to be using this component here it's going to make sure remember that so you one thing you'll notice here is now that we've added the effector it's created this kind of arc this half circle here so this represents the range of the effector so if we change this down here you can see the arc is changing in shape so we'll leave it as 180 and see what happens cool so he's kind of coming through the floor and then kind of landing on and we kind of come at it from the side it's not as bad as before yeah I mean it's not perfect and is with any of these things with games you need to tweak them you know what I mean and going forward if I was making a larger game from this I would probably do a few things I would create more ground checks I will probably kind of duplicate that put one here put one here call it um ground check l oh you know what let's just do it let's go for it what do you reckon let's go for it let's stop mucking around call this one ground check jump actor Visual Studio so we'll want to create expand this condition to check for a few more things so we'll say or let's bring the over in line here and we'll say I'll check L ground check ah put this whole thing in one big condition alright so it's saying if they'll if if there's a line cast between the player and the middle ground check or any of those then let the player be on the floor we've got error here so null are right okay so we need to map those components to the to the player script so here we can see the L&R are still null so we'll drag the L over drag the R over its kind of yeah so what's happening when the player comes off the end I'm gonna just pause then have a look what's going on so it's like it's not why are you not working oh okay I think I know what's going on here let's move these down a little bit yeah there we go that's better so yeah again you just need to tweak these things a little bit and often with the unity with any making any game you're always going to find little things that aren't working so you just gonna play with things there's no hard rules he's gonna kind of play with what it works you should probably be um change into a jump when he falls off I'm noticing that he's breaking into our run see if we can fix that quickly so is grounded if she's not grounded maybe when the player is not grounded here I'm just gonna give this a go so basically we want to say whenever the player is not on the ground you know under any circumstances then flip over to the John frame cool you see that what so now he runs off and he switches to the jump Mega Man yeah boy lovely sky so I'm pretty happy with that that kind of sums it up I think thanks for watching guys I hope you enjoyed that tutorial and please do like and subscribe if you found it useful and there'll be more content coming your way soon okay see you guys

46 thoughts on “Game Dev Basics: Let's make a 2D player controller in C# and Unity!

  1. Why does my character keeps replaying the jump animation after I hit spacebar or even hold on spacebar? Am I missing something out or is it something to do with the groundcheck part? I also didn't typed the if (isgrounded) for both left and right inputs

  2. Whats wrong why i cant move???? I rlly need help

    public class Playercontroller2d : MonoBehaviour

    {

    Animator animator;

    Rigidbody2D rB2D;

    SpriteRenderer SpriteRenderer;

    // Start is called before the first frame update

    void Start()

    {

    animator = GetComponent<Animator>();

    rB2D = GetComponent<Rigidbody2D>();

    SpriteRenderer = GetComponent<SpriteRenderer>();

    }

    // Update func

    private void FixedJoint2D()

    {

    if (Input.GetKey("d") || Input.GetKey("right"))

    {

    rB2D.velocity = new Vector2(2, 0);

    }

    else if(Input.GetKey("a") || Input.GetKey("left"))

    {

    rB2D.velocity = new Vector2(-2, 0);

    }

    }

    }

    // Ty for help

  3. This video helped me so much! Thanks! I have a quesiton though, my jumping animation doesn't actually trigger with anything above 10 Jump Speed. Really frustrating. Any ideas on how I could fix this?

  4. "AssetsScriptsPlayerController.cs(15,15): warning CS0649: Field 'PlayerController.groundCheck' is never assigned to, and will always have its default value null"
    it is assigned, did someone have a similar problem and got the answer?

    btw amazing tutorial

  5. Hey, really cool tutorial! But I have a problem: I wrote the first part of the script exactly as you did, but when I try add it it says that there are compile errors. But in the script itself, there is no error, so I went to the console and there it says ,,There are inconsistent line endings in the 'Assets/Scripts/PlayerController2D.cs' script. Some are Mac OS X (UNIX) and some are Windows.
    This might lead to incorrect line numbers in stacktraces and compiler errors. Many text editors can fix this using Convert Line Endings menu commands.
    UnityEditorInternal.InternalEditorUtility:ProjectWindowDrag(HierarchyProperty, Boolean)
    UnityEditor.DockArea:OnGUI()". What can I do now??

  6. hey just discovered your channel is this beginner friendly tutorial?, am kinda sad and fustrated because i can't understand the code and the more i continue with a series the more it gets complex for me and confusing because i have a hard time learning (yes i have problems with learning) so will this tutorial get me "a basic knowledge about coding in unity 101"?
    Thanks in advance!!!!.

  7. 42:32 That is where I want to be, soon.
    WOOHOO jumping around as Mega man in your own Mega man game, that's just amazing.:D
    PS: I wonder how many people turned game devs because of Mega Man or Zelda:alttp, my guess, most of them.

  8. So much better than all the other 2D PlayerController tutorials I've seen. It's refreshing to see a YouTuber actually create the controller from scratch, as opposed to recommending a 3rd party script. Please do more game programming tutorials!

  9. fantastic tutorial. the only problem i have is the minute i add the && isGrounded part, i cannot jump at all! Please can i have some help? im dying to fix it!

  10. I still have an error: Visual Studio doesnt accept the else statement and if i leave it out and press no keys the player goes automatically in an other way very slowly… pls help i also want this fantastic player control 🙁

  11. Great Bro i am a big fan of mega man. I saw your videos. Doing great. Please do more videos on this. Make a Series on full level design with everything including Boss fight of mega man. Thank you.

  12. When I added the isGrounded code, suddenly my player is falling through the ground. The Ground Check works but collisions seem to not work. Now sure why or how to resolve this.

  13. i have problem with groundcheck: AssetsPlayerMove.cs(13,15): warning CS0649: Field 'PlayerMove.groundCheck' is never assigned to, and will always have its default value null please help me

  14. I have a problem, if I make it so that the player doesn't jump if he is not at the ground, nothing works at all, I can't jump or move. If checked more than 5 times if I have code it correct, but all is correct. Can someone help me?

Leave a Reply

Your email address will not be published. Required fields are marked *