Unity 2D Game Design Tutorial 10 - Moving the player with C# code

Unity 2D Game Design Tutorial 10 – Moving the player with C# code

Views:18139|Rating:4.96|View Time:20:44Minutes|Likes:229|Dislikes:2
This video explains how to move your player in a 2D game in Unity with C# code. After watching this video, you will be able to move your player left and right in a scene using keyboard input. Sample code:

I and welcome to another tutorial on 2d game design in unity in the previous tutorials we've been setting up this scene here in unity for a 2-d game and we've also started some scripting so that we can allow this bulb to collect points when it hits a coin and to make the coin disappear as well and later on we're going to work a little bit more with scoring and displaying the score on the screen and being able to take points off the score as well in addition to be a being able to gain points so we'll look at that a little bit later on but what we're going to do in this tutorial is look at how to actually move our player around so we're going to start working with keyboard input and being able pressed keys in the keyboard to move the player left and right okay and in this example the player will be this ball sprite okay so I'll be moving the ball left and right so we can collect coins and move around the level okay so to get started we need to create a script so we've already got this folder here called scripts so just double click to go in there and there's our coin script from one of the previous tutorials so I'll right click here click on create it will make another c-sharp script okay and this one will be called player controller because it's going to be responsible for controlling the players movement so all one word and start with uppercase P and lowercase C so we can see it's two words there but we're not going to have any spaces in this the name of this script so make sure there's no spaces and now we can go ahead and edit this script but before we do that we might actually drag it onto the asset that we'll be using it which is going to be this ball sprite here so two ways we could do it we could just click and drag and drop it over here on the ball sprite or we can also click and drag and drop it over here it says add component okay and now we can see the player controller script is there so it's attached to the object which is going to be the player in this game so we'll be moving this ball left and right now we can just go and double click on that script which will open up monodevelop and we can start coding okay so here we have a player controller script and we've got all of the default stuff here like using unity engine and system collections we've got the class and we have the start and the update method so what we need to do first inside this player controller class is set up some variables so first variable that will create is going to hold the speed value so speed at which this player will move left and right and that's going to be a public variable that we can access both here in monodevelop where our code is and also inside the unity editor so it's a public variable so we write public it's going to be a float so in the previous scripting tutorial we created a variable that could hold the score value and score is always a whole number doesn't have any decimal places so it was of the integer datatype but for speed we are going to be working with decimal places potentially so it needs to be of the float data type which can hold numbers with the decimal place we'll call it speed and we'll also give it an initial value and we might make it five okay and whenever we work with float values if we're creating a variable and we're giving it a value or changing a value we need to put an F at the end of that value so F standing for float alright we'll create a private variable which will be another float and this will be called movements and we'll have a look at this in a minute and we'll give it an initial value of zero and remember to put F on the in there and we'll make another private one and this is going to be rigidbody2d type so say rigidbody2d and we don't need the equals sign for this we're going to give it another name that we can just fer to in this code which will just be rigidbody lowercase are uppercase B okay so we no need to refer to rigidbody2d we just refer to rigid body okay then we go to the start method and what we need to do when this game began to win this script loads the first thing we need to do is actually get the rigidbody 2d component from whatever this script is attached to which is the ball sprite so if you go back to unity we go to this ball sprite it has a rigidbody 2d which is going to be responsible for the physics and movement of this ball so we need to actually access that rigidbody 2d component in the code so what we'll say is we'll grab that rigidbody variable say Richard body equals get component and then in sharp angle brackets rigid body 2d close that bracket and then open and close normal brackets and in that line with a semicolon so now whenever we want to work with the rigidbody component all we need to do is say we'll just refer to rigidbody just that one we're there so we don't actually need to refer to get component rigidbody 2d we just need to say rigidbody there it's typed as one word and that's it and we need to do we need to access this component at the beginning of the game searching the start method there then now what we need to do every frame of this game inside the update method every frame we need to find out what the movement actually is so whether the player is stationary whether the player is moving left on the horizontal axis or whether the player is moving right on the horizontal axis now we could find out this we could find out maybe what character what sorry what some key the player is pressing on the keyboard so whether the pressing like left arrow or the writer and then we could move the plot or player based on what cane is being pressed but we don't actually have to do that in unity because unity has what's called the input manager so if we go back to unity we go to file sorry edit project settings and input we have an input manager here which has if you click on access we can see we've got horizontal and vertical and the keys that are specified on the keyboard for horizontal and vertical movement are shown here so for example on the horizontal axis so left and right movement we have four negative horizontal movement so moving left on the horizontal axis we have the left arrow key specified there and to move right on the horizontal axis so positive horizontal movement the right arrow key is specified there and then we've got alternative buttons as well a and D and for vertical we have up and down and SW so we're using the a WS and D keys as well as the left right up and down keys on the keyboard for horizontal and vertical movement so we don't actually have to in the code specify what keys are being pressed to move the character in certain direction because it's all specified here so all we need to do is just get to be able to move the character left and right is just get the horizontal axis so what we'll do is we'll go back to the code and we'll say we'll get that movement variable that we created earlier and we'll say movement equals input dot get axis and then in brackets and double quotes horizontal so we want to get the horizontal axis and close that in that line over the semi column so at the moment we're only working with horizontal axis we don't need to worry about the vertical axis a moment will work with I'm getting the character to jump will move up and down in the next tutorial but at the moment we just want the player to be able to move left and right in the scene so this move variable here will hold negative and positive values between minus one and one for left and right movement so if the character is stationary not moving at all the movement will be equal to zero and if the player is moving left it will be a negative number and down to minus one so they're moving at full speed left we've got the left arrow key down or the a button held right down then it will be minus one okay but if they're moving right then it will be a positive number up to one so if they're holding that button down it'll be one so what we can do is we can actually go and check those values right now without actually getting the player to move here we can just see what values we get when we press those buttons so we could do a debug log message so we could show a little message in the console and we can just output the value of that movement variable and we go and save that script and go back to unity and we can go and run this game and go to the console and don't worry about any little messages there at the moment but what we can do is we can press left and the ball is not moving left when we press the left arrow but we can see that we get oops could actually click inside the game here when we press the left arrow we can now see that we get negative values here so it wasn't coming up because I wasn't actually in the scene I had to click a mouse on the scene but if I press the left arrow key or if I also press a we get negative numbers there if I hold it down it becomes minus one so if I hold it down it is it because minus one will very close to that now if I hold down the right arrow key it will become a positive number so I keep tapping it you can see we get positive numbers if I hold it down we get like pretty much one or very close to one okay and same with D okay so we're just getting a little message here in the console just showing the values for if I'm moving left and the values but if we're moving right so you get negative numbers and positive numbers okay but we're not actually moving it we haven't specified movement yet so let's go back to the code and we can get rid of that message now we don't necessarily need that what we can do now is there's two methods I'm going to show you for moving the character so first method here is we're going to make velocity equal to our movement speed value so what we'll do is we'll say rigidbody dot velocity equals new vector 2 and a vector 2 is going to store to hold two values the first one is for the x-axis and the second will be for the y-axis say new vector 2 and for the x-axis we want to make velocity equal to movement x speed to movement x speed so what this will do is it will get movement so movement is equal to if we're moving left it's a negative number down to minus 1 we're moving right then it's a positive number up to 1 so whatever movement is we'll multiply that by speed which is 5 and that will be a velocity for the x-axis okay and then we also need to specify for the y-axis and we're not actually working with the y-axis yet we're not moving the character up or down yet so what we'll do is we'll make Y velocities they equal to what it already is because we're only working with the horizontal axis at the moment so we can say rigidbody dot velocity dot y and we can end that line with the semicolon we can save that and then we can go back to unity and we can go and run this and now what I'll do is I'll move left when we've right so I'm pressing the right arrow key now you're pressing the left arrow key and we can do that again with D to move right and a to move left so this works okay and you notice when I press so now I actually I'll stop pressing any keys on the keyboard as soon as I stop pressing keys it just stays there wherever it is and also notice that doesn't really roll down the hill like it did before so before we added this code the ball would drop down these planks and roll along the grass but at the moment while I'm not pressing any Keys it's kind of it is rolling but really really slowly so it only actually moves properly when I press one of the keys okay so that's the first method and a reason why it's doing that a reason why the ball I'll just show that again the ball kind of lands there and instead of rolling down quickly and rolling down here and collecting the coin it's just kind of moving really slowly reason why that is is because if we go back to the code every frame so every time this update method is called every frame movement is equal to input get access horizontal so movement while none of the keys are being pressed movement is going to be pretty much zero all right it should be zero so velocity is going to be equal to also equal to 0 on the x axis okay because movement if it's zero as x speed or zero times five is zero so it's not actually really going to be moving so the only reason why it's moving a little bit is probably because the gravity settings on the on the rigidbody and making it move a little bit but we can do is we can make this player move only when the keys are being pressed so we can make the character move left and right only when we know that the keys are being pressed to move it left and right and so we can keep we can basically not affect the movement or look like of the of the ball making it move around fall down these planks until the keys are being pressed so we can do that with some if statements so let's go back to the code and what we'll do is we'll keep this line here but we'll put it inside an if statement so say if then in brackets we'll specify a condition here if movement is greater than zero and remember it's a a float so we need to put F if movement is greater than zero and we can put a curly bracket here and curly bracket here and what that will do is basically it will set up the condition here so if movement is greater than zero then whatever is inside these curly brackets will occur so basically if movement is greater than zero it will move right okay so it will move only if the right arrow key is being pressed or the D key is being pressed and then what we can also say is LCU movement is less than zero and again we need some curly brackets here just move that down a bit we can go and copy that code it's exactly the same we can put it in there and so now we can say if movement is less than zero then move it as well so it's only moving right if movement is greater than zero it's only moving left if movement is less than zero in other words it's only moving if the movement value is not equal to zero a so if one of those keys is being pressed so let's say that code and go back to unity and run this and now you can see that the ball is able to roll down I've got gravity going on we've got this ball moving down slopes but if I press left it can move left if I press right it can move right as well okay so we've got our player movement here with the keyboard but with we can also allow the ball to move freely on its own according to gravity and different forces okay so another thing that we can do is if we go back to the code if if we don't want this ball to really move at all when none of the keys are being pressed so we can also do that with code we can just say else and then some curly brackets here and a kind of like all of my if and else statements on separate lines so I'll just make some room now so we can say else and then we can say rigidbody dot velocity equals new vector2 and we can say zero for the x axis so it's not going to move at all on the x axis if none of these no keys are being pressed to make it moving so you can say zero and then we can just keep velocity for the y axis whatever it is already equal to so rigidbody dot velocity and just make sure that you change that back to what that's meant to be if it auto corrects it to something else just make sure that rigidbody is exactly how it Finch big so we created this variable up here with lower case and upper case B so make sure it's that dot velocity our Y and you might also want to just to prevent the autocorrect happening there maybe call this something else like my rigidbody or play a rigidbody or something like that anyway that's what it is now we'll save that go back to unity run this and it's kind of back to how it was before so it's not moving at all really unless a key is pressed like I'm doing now so left and right oppressed and then when nothing's pressed it kind of comes to a stop and doesn't move all right so that's basic player movement in unity a couple of different ways that you can do it there so a really simple method and then another method using if statements to detect movement but that's basic player movement in unity with not really a lot of code there in the next tutorial we're going to look at how to make the player jump thanks for watching

23 Replies to “Unity 2D Game Design Tutorial 10 – Moving the player with C# code”

  1. billyblackburn87

    sorry that c# code was horrible.

    Do this instead:

    if(movement > 0f || movement < 0)


    rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);



    rigidBody.velocity = new Vector2(0, rigidBody.velocity.y)


  2. Rrrush

    So what i dont get is that when theres a hill add force is apllied to push me down adding force. But when i simultaneously move up the hill it still pushes me down when i want to go up. Hmmm..

  3. Some Things I Like To Share

    Hi, Thanks for the amazing tutorial, I learnt a lot and it's quite informative. We can say movemoent is != 0 and else in update method

  4. Ethan Popovich

    Hi Daniel, I came across a few of your tutorial videos and thought you did an excellent job explaining the martial. I was wondering, have you ever developed a game?

  5. Adam Hickey

    The code in this one definitely could have been condensed to reduce the conditionals. Either way, great tutorials. Thank you.

  6. slinkydog247

    hi Da, Loving the videos bud, i'm completely new to unity and c# if it wasnt for these vids i woulda been lost man lol, great vids, keep up the good work mate

  7. Eduards Bistrums

    Cleaner code:
    if (movement > 0f || movement < 0f) {
    rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);

Leave a Reply

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