If you have problems jumping, check if you set the layer mask correctly, the jumpspeed isn't 0, and that the Jump function is getting called. You can also try this jump function instead: private bool IsGrounded() { Vector2 feetPos = transform.position; feetPos.y -= col.bounds.extents.y; return Physics2D.OverlapCircle(feetPos, .1f, ground); } Which is similar to the other but uses a different Physics2D function. If there is an issue with spamming the spacebar then here's the fix, just pass in the float value in to the Jump Function and then in jump check if that value equals 1: playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue()); ... private void Jump(float val){ if (val == 1 && IsGrounded()) { ...
It seems that isgrounded is returning true even after you are not technically grounded. Try changing the radius of the Overlap Circle and make it smaller.
It is easier to implement but using colliders like that is not always super accurate that's why a lot of platformers use raycasts (that's a whole topic though). Here we are making a function to extend from the boundaries of the collider to make sure it's touching the floor.
I checked and tried so many tutorials about the new input system and got confused more until I saw this one. I understand perfectly and working perfectly on my own project, Thanks a lot! ** YOU ARE SO TALENTED**
For those who have problems spamming the jump key, when we assign the "Ground" layer in the "PlayerController" script, we must unassign the "Default" layer, since if not, both are marked and it always detects a collision in the function " IsGrounded () " Greetings!
In my pinned comment to this video I also have a fix for spamming the jump key which is a one line addition to the code if you continue having issues 🙂
I have a rule I'm making for myself wherein I won't implement any code unless I fully understand it and you provided A LOT of things to break down. Thanks again!
You just took something really difficult and made it easy. Been seeing a lot of stuff, from unity and a bunch of other sources, saying to use "InputAction.CallbackContext" but it always returned an error for me. I didnt even know I needed to generate a script from the input system, I thought it was some type of global value stored somewhere. Thanks!
inorite! I had no idea you had to explicitly generate the script with the check box on the asset in the project view before anything was hooked up. I was pulling my hair out trying to figure out why my input events weren't making to the associated script until this video.
This was great! I've been searching for a while to find a more recent video to make a good player controller, but most are from years ago and are pretty much obsolete now. These two videos helped me immensely. I did find one issue. If the player presses space to jump but holds it down, letting go of space has the player jump again.
Glad you liked it! That's my bad, it's because the Jump method gets called whether you are pressing down or up on the key. Here's the fix, just pass in the float value and then in jump check if that value equals 1: playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue()); ... private void Jump(float val){ if (val == 1 && IsGrounded()) { ...
A year too late, buuut just in case someone wonders the same issue, change Action type to Button rather than Pass Through on the PlayerControls input aciton
In case someone else out there is NOT working with a tile map and cannot get the Jump function to work with the 'ground' layer this is what i did that worked. I am working with an empty gameObject with a 2d box collider as my floor whose Layermask is set to "ground". Only way i got the Jump portion of code to work was to change col =GetComponent(); I then placed a 2Dcircle collider onto my 'Player' gameObject and set radius to 2 and offset Y axis so the bottom of circle is at feet of my Player sprite (in my case 1.37) hope this helps somebody! And great tutorial btw! Def recommend!
It also helps to remember space bar is the jump key. Really great tutorials though. They've really helped me learn Unity and understand certain things I did in my college game math and physics class that I didn't get at the time despite passing the class lol
I am running into one bug with this script, the jump functions occurs on both the press and release of the jump key when in contact with the ground. But this is a VERY nice and straight forward tutorial. Clear, concise and not too much hand waving of details that most tutorials have. Thank you!
Great videos! I decided to revisit the new Input system since I'm using Unity 2020 now. I feel like a lot of people made videos about the system a year ago but never revisited it. Also, I seem to recall that making use of the system was much more manual (I don't remember the tutorials I went through having the C# code generated - not sure if that was just them trying to do things very customized or if that feature wasn't implemented at that time). Anyway, you explained the material well, your steps were easy to follow, and now I feel like I know exactly what is different between the legacy and new systems, and no longer feel like the new system is overwhelming and cumbersome! Keep up the great work!
Finally after two days of trying out a lot of different tutorials of youtube and unity the last 2 days i can use the new input system thanks to you. will stick to your videos now to make the base functions of my game =) Unity did not provide good videos for the new input system and i couldnt find their own controller script -.-^^
Thanks awesome video . I'm using the rigid body component to move my player, for people who wondering why their player not moving they should replace the movment.y = input.GetAxis("Vertical"); to movement.y = controls.Gameplay.Move.ReadValue(); so it takes the new input. In my case I want to move my player vertically so I used the y axis.
Thank you very much.The reason I wanted to try out the Input System is because Input.GetButtonDown isn't always responsive while running and it was really frustrating,now the jump movement works perfectly fine,thank you very much.I just have a small suggestion for you,instead of using if (IsGrounded) you could just use if (collider.IsTouchingLayers(ground)),which makes it more easy to remember and understand.
after watching some other videos on the new input system and not being able to make it work, I found the previous and this video and you saved me a massive headache. Everything was well explained and everything worked well, thank you so so much! I subscribed and will be using your videos in the future to keep learning :)
LOL okay so I followed everything relaly well a nd totally broke down right around minute 14:00... I was like OMG I'm not understanding where things are getting referenced anymore! Haha I'm sure if I watch it over and over and google around I will figure it out however when you said, "If this seems complicated, it's because it is," you were right!
Great tutorial in running through the (new) input system. I'd love to see something more complex like when you want an action (eg. boost) that only works when you're *holding* a button. Regardless, thanks for taking the time to explain it to a beginner.
Sure! I have a hold feature that I cover in my Line Rider series (Make Line Rider in Unity Pt.1 - Input System Manager ua-cam.com/video/Y1BQoAmTC2s/v-deo.html). There is also a Hold interaction you can add to your actions, where it will only be performed if it is held down after a certain period of time. However if you want to continue to execute something while it's being held down you need to store a variable that's set true when you start pressing and false when you stop
We have a winner here! Simple and Clear to understand. Regarding the IsGrounded function, couldn't we simply use an rigidBoby.velocity.y == 0f check instead?
This is lovely work honestly been trying to learn more on how to use the Input system with 2D. Only issue I came in with is the "Spam" space button deal. I would be lying if I didn't get a chuckle signing the "you can fly" part from Peter pan when I'm trying everything thing I know and what you recommend.
@@samyam Well after I put into it was most likely a sprite issue Idk I was using sprite or it was the just I did the ground wrong either way it's fixed.
Great video! Thank you for using the new input controller too, I was wondering how that worked. How would you go about adding gravity to the player at the apex of the jump to make it less floaty?
Oh, one more thing. Rather than have the move function in the Update() method which can cause jitter when the collider boxes of the player and env walls make contact, ppl should instead use the FixedUpdate() method. This removes the jitter. Also, I am curious why you used Vector3 instead of Vector2? Thanks again for making this! Was super helpful and I've already learned a TON from this jumping off point.
For those that want details, Update() updates on each rendered frame, while FixedUpdate() updates based on the physics calculation in Unity, so Update() can can slow or speed up based on how intensive you graphics are while FixedUpdate() keeps all your physics calculations in sync. If you put physics based code to update via the Update() method you can get strange physical behavior like jitters in transforms and what not. stackoverflow.com/questions/34447682/what-is-the-difference-between-update-fixedupdate-in-unity
You should do only physics related calculations/movement in fixed update, instead you can try selecting Interpolate in the Rigidbody component so it smoothly changes position
The input system had been baffling me for too long! Thank you so much for this tutorial! I think the method you used for ground check just might make it easier for me to add a wall jump ability. If I add a similar function for wall check, do you think I can read which side of the player the wall is on and jump from there? How would I go about that?
I would recommend using raycasts instead for detecting both wall and ground, basically shoot out some rays sideways and downwards (the ray will be small 0.1f or similar distance) on every frame and store the collision.
Hey, thanks for this tutorial! I was looking at Brackeys' video before this, and it was helpful, but I felt like I couldn't translate what I learned there into a 2D game very well. This helped tremendously!
Thanks SOOOO much for the video!! I also need to make a local multiplayer version. are you able to make a video showing that? None of the other videos I can find seem to work and combining your teaching with someone else's multiplayer videos is just confusing me no end! I hope you can help cause you're extremely good at teaching!!!!!!!!!!! :)
as a programer myself the jumpspeednsounds just silly maybe jumppower, jumpstrengh, jumpforce but jumpspeed mean to me how quickly player lands than jumps so its just kinda wrong great tutorial ☺ tho 👍
Did I miss a step for preventing the player character from falling off the end of the ground if I move too far to the left. I created the TileMap collider which I use to only allow jumping when on the ground, but if I move too far to the left, I fall off the platform. Do you have a recommend technique for preventing movement beyond the end of the ground?
Thank you very much for this tutorial, it really really helped! aside a funny thing where it launches me into space if i spam the jump key, it works great! i'm not sure if this is a dumb question though, but how would you handle crouching?
Glad you enjoyed! Make sure the isgrounded function, player collider, and layermask is correct, should only be able to press jump when on the ground. For crouching you will need a crouching animation and you would just decrease the size of the player collider when crouching so it can pass under objects (and then set it back).
Thanks for this! Very clear explanation. Dumb Question: Is there a way to assign a bool to a var like with the old system Ej: jumpPressed = Input.GetButtonDown("Jump");
Glad you enjoyed the video! With the input system it calls a function whenever it's executed, as we did with the Jump, so you could set the boolean in the function itself if you needed to. There's other callbacks for actions such as started and canceled where you can set the boolean to true or false or do some other effects. Also if the value is a float with the value one or zero, in the function you can just set the value to a boolean since 1 = true and 0 = false. Convert.ToBoolean is a C# function you can also use to convert an integer to boolean too. Let me know if that helps!
at 9:54 i have an alternative method for the same thing! at the time stamped place IsGround = Physics.CheckSphere(findGround.position, groundRadius, groundMask); into the Updates first line then have 3 small things at the top; public LayerMask groundMask; public float groundRadius public Transform findGround; then then the () away from the IsGround bool if (IsGrounded) { rb.AddForce... } thank you tho for the intro to the input system!!
Great tutorial! I’m not sure if this is a dumb question, but how would you add animations and how would you add in more complex movement such as a dash?
No such thing as dumb questions I have these two videos that might help How to Set Up an Animator Controller with Sprite Sheets - Unity Tutorial ua-cam.com/video/1Ll1fy2EehU/v-deo.html Animator Controller Scripting - Unity Tutorial ua-cam.com/video/3Ad1wr3qBRw/v-deo.html As for a dash you can listen for the dash button and add force to the player in that direction (or you can lerp to a location over a certain duration (i recommend a coroutine for this but it can be done in update)) Here’s a simple example blackthornprod made ua-cam.com/video/w4YV8s9Wi3w/v-deo.html
I have a similar video for 3D movement but it uses joysticks, you can easily remove the joystick however Mobile Joystick with NEW Input System and Cinemachine - Unity 2020 Tutorial
Samyam, love your tutorials on the new input system. Question for you, do you know how to resolve actions performing twice? If you press jump and hold down the button till your player hits the ground. On release of the button the player will jump again. I discovered this issue when creating a shoot function following your other tutorial. I can't seem to find a way to make the button only function once.
Hi Qlawen, did you try my suggestion on the pinned comment to this video? I added a fix for that there: ``` If there is an issue with spamming the spacebar then here's the fix, just pass in the float value in to the Jump Function and then in jump check if that value equals 1: playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue()); ... private void Jump(float val){ if (val == 1 && IsGrounded()) { ```
couldn't find ANY documentation about applying vector forces / getting the transform using the new input system online. Was searching for DAYS. How did you find this information?? Do you have access to some top secret Unity development bunker?
Great video! I'm working on a top-down 2d game, and I want to implement a shooting mechanic. In the old input system it was very easy, but I can't make it work with the new one. Please help me!
I have an error in unity that says Assets\Scripts\PlayerController.cs(34,6): error CS1519: Invalid token '-' in class, struct, or interface member declaration What should I do. It wont show the jumppower or movespeed in unity.
You can double click the error and it will take you to the line where the error is, it seems you have a syntax error on that line (misspelled something)
Hi samyan! When i jump next to a wall i get infinite impulse. How can I fix it? The map on my project is tile based and have a tilemap collider 2D and a composite collider 2D. Thx in advance!
@@samyam Sorry english isn't my native language. I uploaded a video where you can see the normal jump and the jump when I'm close to a wall. That's what I mean with infinite impulse. ua-cam.com/video/S487V8uwCqA/v-deo.html
What do you mean by jump multiplayer (do you mean like a double jump or adding in a speed)? You can do those through code in the update function, just with a different input type.
Thanks for the great tutorial but I am having an issue with the jumping. My character won't jump when standing normally, but if I push my character up against a wall it will jump. I'm wondering if maybe there is a way to expand the square used for checking if it is grounded down further than the box collider?
@@samyam Thanks so much for the help. While playing around with it some more I discovered that for whatever reason if the top of the box collider is bellow the middle of the character the ground check glitches out and doesn't work.
What do you mean weights? Like a priority? You could possible write a custom component docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/ActionBindings.html#writing-custom-composites
The tutorial video's are a great help but I ran into an error and dont know what to do about it I have only done the moving sideways part so far. I did the exact same things like in the video but my Unity keeps giving me an error message :Assets\Scripts\PlayerController.cs(35,61): error CS1061: 'InputAction' does not contain a definition for 'Readvalue' and no accessible extension method 'Readvalue' accepting a first argument of type 'InputAction' could be found (are you missing a using directive or an assembly reference?) I've remade it trice but I get the same result every time
Make sure you are accessing your controls and action correctly, it seems like you are using the wrong names. General syntax is like this ...ReadValue()
thank you for this tutorial miss i've enjoyed it as much as it helped me but can you please teach us how to flip the player when it's moving? :) (i hope this doesn't sound rude or anything it's just english is my second language)
Thanks for watching! This video is actually part of a mini-series and I cover that in a video later on, specifically the Animator Controller Scripting Video ua-cam.com/play/PLKUARkaoYQT178f_Y3wcSIFiViW8vixL4.html
I've been following this tutorial, it was going fine untill i got "error CS1585: Member modifier 'private' must precede the member type and name" on line 12 "private PlayControls playcontrols;" do you know how to fix this? if so please tell me. thx
Great tutorial - but where have I messed up? My player only jumps when their layer is set to ground, and then naturally jumps like flappy bird in mid air as if they are always in contact with ground. All layers are in the right order and the player collider does not overlap. Have tried every combination with alternating layers turned off an on. I have done this to render it impossible for the player collider to be in contact with anything while in the air. Yet the input still has the player 'jumping' while in mid air. All code correct and accounted for as directed in the video. have tried below solutions but to no effect.
Thanks for your work! I have a question for you: I am using a Plugin from the asset store that uses the old input system (Pixelcrushers Dialogue System). In the Project Settings I've set "Active Input Handling" to "Both" so I can use the plugin AND the new input system. Do you know if this has any impact on performance? Would you do it like this, too, or rather stick to one input system? (In my case this would mean to switch back to the old one. My game has very simple controls, so complexity wouldn't be an issue. I just prefer the new input system bc it seems so much easier and straigth forward to use)
That asset supports the new input system :)! ua-cam.com/video/iUoD0eDZPWw/v-deo.html I rather stick to one if possible, but if an asset must use the old one then there is no way around it. But I'd still use the new one to do the main input mechanics (so switching to Both).
@@samyam Thanks for your reply! Oh, damn, it totally didn't occur to me to even check whether the asset supports the new input system because i had already got so used to it using the old system *facepalm* Double thanks for answering an actually stupid question ;)
So my problem is that the player partly merges into a wall when he walks into it (even midair), and this gives the player an opportunity to jump again. Any help is much appreciated! edit: just being too close to a wall makes the player able to jump as well.
You can try putting different colliders on the walls that aren't marked as ground, you can also try giving the wall a physics material with no friction, or you can try doing raycasts for collision instead and shoot raycasts under your player to see if they are grounded
@@samyam thanks! I will try that. Quick note: I thought this bug was interesting since you can hop up walls so I decided to make the player bouncy and keep it. I will not keep it in my future projects though.
Yeah, the input system detects where the inputs are coming from and switches automatically, just make sure the action type is not set to Passthrough. At the top left you can add a controller scheme. I'll look into making a video on this.
@@samyam I'd be very thankful, i'm having a lot of trouble using the new system and there aren't much up to date tutorials about it especially on how to use stuff like accelerometer, gamepad.
First off, nice vid. Secondly when i add the first new component to my player to add the player controller script component it doesnt allow me to put in anything. It just says what script im using. It did work first but when i removed the component then added it again the problem happened. Do you know what wrong?
I just found this error message if it helps: Assets\Scripts\PlayerController.cs(12,9): error CS0246: The type or namespace name 'Void' could not be found (are you missing a using directive or an assembly reference?)
Hi Jesse, you won't be able to add the script to the game object if there is an error on it. In the console window on Unity (Window->General->Console) could you double click the error and paste here the code you are talking about? You might have accidentally changed something on that line.
I followed all the steps but when it comes to the cube and you have to add the player controller its doesn't pop up even tho I have the c#script right there any advice
Hey there anyone who sees this, I have an interesting situation that I am trying to solve: I'm trying to create a simple switch in my game. The idea is that when the player is touching the switch, and they press the a button it will open a door, and possibly do other actions down the line. Trouble is, I cant seem to use both the button press and collision both as conditions at once. The main reason its not working for me (as far as I can tell) is that I cant seem to place the button pressed into an if statement. Ideally, I would like it to work something like this. If(Player collides with something && A button is pressed){ Do something. } So basically, what can I use within the new input system to determine if the player has pressed the A button, in the context of an if statement?
In the old Input Manager we can set the gravity and sensitivity so that button presses return a float between -1 and 1. In the new Input system, using the 1D axis only seems to output 0, the min value or max value. Is there a way to recreate this in the new input system?
According to the documentation the Axis Composite should return the values “This means that if the buttons are actual axes (e.g. the triggers on gamepads), then the values correspond to how much the axis is actuated.” They also have an Evaluate Magnitude method that returns the current magnitude, which is probably what you are looking for. docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.Composites.AxisComposite.html
@@samyam Thanks for replying and sharing the doc. After more reading up on it I found that what I'm looking for is sensitivity (digital input get smoothly increased to its max value (of 1)) and gravity (digital input gets decreased continuously to 0 after releasing). I want it to smooth out the movement when using boolean inputs like standard keyboard keys. There is a solution here but I don't understand it yet so I'm not certain it works: forum.unity.com/threads/so-how-do-i-get-input-getkeydown-a.939347/#post-6138555
I've found that I can recreate this using 'Mathf.MoveTowards' ... currStrength = Mathf.MoveTowards(currStrength, maxStrength, acceleration * Time.deltaTime) Where maxStrength is set to the movement input value (-1, 1, 0) on every change. I then would use currStrength instead of where you have movementInput.
Yes in update you can do If (playerActionControls.Land.Move.ReadValue()!= Vector2.zero) etc... Basically it's saying if we are moving then do something. The way I'm doing the movement is similar. With the jumping I'm just saying to execute the jump command when we perform our jump action.
even if this video was made in mid 2020 and now it is almost 2022, I am completely stuck on this one thing, when putting the player controller on the cube when you type it in it automatically pops up, but for me no such component exists then when trying to add it as one, it just creates a whole new PlayerController script!
Yes, I know the 3rd Person tutorial. But I can't add the component which you add to convert the cinemachine for the new Input System. I don't know why. Perhaps because I still work with the 2019.4 version. I am installing the 2020 LTS right now and will try it again. Thanks for the response. 😊
samyam I've been using Unity off and on for years and if there's one thing that's stuck with me more than others, it's that moving objects through their transform when they need to interact with the physics system is just bad form and asking for trouble. Like the object not responding to collisions properly. The only reason I can think of that it might be ok to move an object with transform rather than a rigidbody is if that object doesn't need to interact with the physics system. So why teach people this way instead of rb.velocity or rb.position?
In an actual game (platformer), I recommend using custom physics and moving with Translate/position rather than rigidbodies at all. However this meant as a beginner video and that would take a whole series to go through (Sebastian Lague's 2D Character Controller). I do agree that using transform position while also having a Rigidbody does cost more performance and can lead to unstable collisions since the rigidbody calculation is done after the transform position changed. According to Unity documentation, Rb velocity is more useful for changing the velocity like when jumping and not really meant to be changed every frame. The rb position is also meant to be used to move instantaneously to one location.
@@samyam Thanks for taking the time to get back to me and I appreciate the thorough response. I'm just recently getting back into Unity after a while away, which is how I came across your channel, and looking through beginner videos has been helping me to relearn things I've forgotten and learn things I missed before. I'll keep in mind what you said and look into Sebastian's videos also. Thanks and take care!
why not ? horizontalInput = Input.GetAxis("Horizontal"); transform.Translate(Vector3.right * Time.deltaTime * horizontalInput * speed); is there any performance different ?
How could this be changed so that the character can go up and down on a map while still also being able to jump? Mind you I have no idea how maths work--and I tried rejiggering the code so that the inputs became Vector2 and 2D vectors...my character (i'm still figuring out how to move across a tile map or whatever) could go back and forth on the collider i'd set up (just the plain green box) and they could jump and ostensibly move up and down (if i froze the y axis they could move....wait I just answered my own question....you can't have Y upmovement and a jump feature at the same time...or can you!? (also it made it so the animations stopped working except for idle and jump....I don't know if i'm making sense.
Not sure I understand 😅 I have a video on top down movement but I don't think that's what you are looking for. Do you mean like freezing in the middle of a jump? ua-cam.com/video/H2RLv0aWUB0/v-deo.html
So I set everything up and used the ctx trick in the pinned comment, but I have some platforms with my ground layer, and if you just spam spacewhile directly in contact with the side of the platform you can get HELLA extra height. How do I stop this from happening?
In that case you might want to use a raycast 2d and shoot a ray downward from the player to check if the ground is there (it's another way to do ground check). Most people have multiple raycasts (3, two on the ends and on on the middle) for better detection of the ground especially if you are on an edge). Here's an example kylewbanks.com/blog/unity-2d-checking-if-a-character-or-object-is-on-the-ground-using-raycasts Their distance is pretty large in the example, might want to reduce that to maybe 0.1f.
Hi, I am trying to setup a multi-profile input system. In which based off the binding options the user selects, the game will use it to match to one of the preset input profiles. My issue is in the line where you pass the performed jump into the jump function. It is setup where you have to choose a single profile ("Land" for example), but that doesn't work if a different input profile is being used. I tried to insert some sort of string variable to make the profile dynamic but I just don't know what to do based on how the syntax messes up functions like .ToString()
If you mean switching the action maps you can do something like this: player_input.SwitchCurrentActionMap(player_input.actions.GetActionMap("Player").id); When the player selects a profile you can store the map string associated with it and then pass it to the SwitchCurrentActionMap function.
@@samyam that works however doesn’t solve the syntax issue with character controller script. Jump is done using “PlayerControls.Profile.Action.Performed” and the “profile” part of it is static. So if I switched input profiles it wouldn’t work anymore and I’m not sure how to solve it. I tried using a variable for the profile name and couldn’t figure it out
I see, try using the PlayerInput component where you can switch out the active action map but keep the code the same. playerInput.actions[“Move”].ReadValue()
@@samyam ok thank you! If that doesn’t work my other idea was to just add a bunch of listeners with all the different combinations and then for the composite movement I would just add all the listeners together into the single movement variable if that makes sense. Also thank you for these tutorials this is the only one I was able to actually understand what the code meant and how to apply it :)
hello samyam i have a problem i try to solve it over 8h now but idk, i make step for step and it works so i can move but i get everytime i press the "A" or "D" key this error "InvalidOperationException: Cannot read value of type 'Vector2' from composite 'UnityEngine.InputSystem.Composites.AxisComposite' bound to action 'Land/Move[/Keyboard/a,/Keyboard/d]' (composite is a 'Int32' with value type 'float')" i hope u can help or somebody else?
Are there are errors? Check Window>General>Console and make sure there are no errors. You can also put Debug statements ua-cam.com/video/vy7WXLArj4U/v-deo.html or breakpoints to find bugs or errors in your code.
I think I'm missing something. I tried adding the "[SerializeField] private float speed, jumpSpeed;" but when I add the PlayerController comment to the cube, I don't see "speed" or "jumpSpeed". Can anyone help? Do I have to do something to MS Visual Studio?
You have to have a SerializeField separate per variable. [SerializeField] private float speed; [SerializeField] private float jumpSpeed; Let me know if that helps.
Thank you, mam, it is a great series just a small help my code is correct in fact everything is as you stated still my character doesn't jump. Please help mam
I have pinned a comment to this video regarding this issue, check it out and let me know if those work. Make sure the layermask is correct, jumpspeed is not 0, and that the jump function is getting called.
InvalidOperationException: Cannot read value of type 'Single' from composite 'UnityEngine.InputSystem.Composites.Vector2Composite' bound to action 'Land/Movement[/Keyboard/w,/Keyboard/s,/Keyboard/a,/Keyboard/d]' (composite is a 'Int32' with value type 'Vector2')
heyy when you are typing something in the Visual Code Editor ,how do you get suggestions bcoz i was not getting some suggestions while I was typing. Also my Player Controller script doesnt work means I don't get the option of changing speed and jump but i have followed every step of yours. :(
I have a video on setting up visual code with suggestions ua-cam.com/video/4WWX2_tZu5Q/v-deo.html If you mean you can’t see the speeds in the inspector, make sure you put a SerializeField on both of them. Also make sure to check the Console (Window>General>Console) for any errors in your script
@@samyam sorry for irritating you but I now realized that when I click play it says that compiler errors must be fixed So what could be the reason for that? Sorry again for taking your valuable time🙏😕
No problem! It means you have errors on your script that you have to fix (Window>General>Console) You can double click the error and it will take you to the line where the error is. And the description of the error usually helps in solving the problem. I have a video on console and debugging that might help ua-cam.com/video/vy7WXLArj4U/v-deo.html
hello thanks for great tutorial i have some issue everthing works until jump unity give me error Assets\Scripts\PlayerController.cs(40,8): error CS0103: The name 'Phsics2D' does not exist in the current context definition for ground [SerializeField]private LayerMask ground; return Phsics2D.OverlapArea(topLeftPoint,bottomRightPoint,ground); same as you do far as i can follow the tutorial can you give me little guidence what can cause this becuse everthing looks correct to me
my character does not jump anymore i was adding an idle animation and while doing that everything broke, my colliders and ground, ceiling checks had all been moved up and i could no longer jump, do you know what the problem is?, it doesnt say theres any errors in the code so im really lost on this one
Hard to tell without seeing the project, try setting the player on a simple cube with a collider and trying to debug from there I have a video how to debug log here ua-cam.com/video/vy7WXLArj4U/v-deo.html Also setting breakpoints would help walk you through the code. Make sure you also have the layer for Ground set correctly
Welp my character jumps but only when a platform is above him not under him lol. I tried changing the Vector2 +=/-= lines (lines 40-46) to match each other, reverse of what you wrote or any other combinations but nothing :/. Im assuming that might be the culprit but any help would be really appreciated!
Maybe it’s because the overlap area it’s checking isn’t on the player correctly. You can paste the portion of the code here so I can take a look, you can also try using another function to detect collisions docs.unity3d.com/ScriptReference/Physics2D.OverlapBoxNonAlloc.html
@@samyam Thank you a lot for getting back to me so quick. Lol now I don't have to wait weeks before hearing a response like other youtubers. Def just earned yourself a new subscriber! But I noticed that if my box collider is ridiculously large on the y size (about 3 times my character's height) it works normally as intended but trying to bring it down to my character's actual height and nothing :/. Here is my code for lines 46-58: private bool IsGrounded() { //Positions for Grounded Collider Vector2 topLeftPoint = transform.position; topLeftPoint.x -= col.bounds.extents.x; topLeftPoint.y += col.bounds.extents.y; Vector2 bottomRightPoint = transform.position; bottomRightPoint.x += col.bounds.extents.x; bottomRightPoint.y -= col.bounds.extents.y; return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground); }
Ah ok I think I figured out the issue. The box for my rect tool is a lot larger than my object so anytime the collider is outside that box than it will allow me to jump. Do you happen to know how to shrink that resize rect tool box (lol the one with blue dots at the corners) back down or in line with my actual image/object? Sorry if thats confusing lol
@@samyam its something with actual rect box for the sprite. Lol sorry could've said its a sprite imported from Aseprite but I found out the issue. Its using the whole area of the canvas instead of just cropping down to what is drawn. But what you said also made my life a lot easier! Thank you again!
hello i tried using your tutorials and i wondered if you know why it says that "playerActionControls" is not found in the global namespace? can you help me :D
That’s the variable we declare at the top of the class for our controls, maybe you forgot to declare it? private PlayerActionControls playerActionControls;
@@samyam i am really sorry for taking up your time but i am really sure that i did declare it i just added my code here: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControls : MonoBehaviour { private PlayerActionControls playerActionControls; [SerializeField] private float speed, jumpSpeed; private void Awake() { global::playerActionControls = new PlayerActionControls(); } private void OnEnable() { playerActionControls.Enable(); } private void OnDisable() { playerActionControls.Disable(); } void Start() { } void Update() { float movementInput = playerActionControls.Land.Move.ReadValue(); Vector3 currentPosition = transform.position; currentPosition.x += movementInput * speed * Time.deltaTime; transform.position = currentPosition; } }
error CS0246: The Type or namespace “PlayerActionControls” could not be found (are you missing a using directive or and assembly reference?) shows that error when I finish the coding part. Any help?
The jump is physics based, the movement is not. If you'd like to implement a unity-physics free character controller based on raycasts I recommend Sebastian Lague's Character Controller 2D series.
Unluckily it works with this 3D Box, but not when using a rigged animated character inside a "game objekct" - my character moves sideways but can jump to infinity, with the same settings.... :(
Are you talking about the box collider? If so I use a 2D Box Collider not a 3D one. Make sure the collider is not super big or else it will register on the ground when it's not. I also have some other suggestions in my pinned comment to this video, if you expand it I have a fix for a spamming the spacebar bug.
so i copied everything correctly, or so i thought i did, i got stuck at 4:20 (wow how perfect) the component does not have the same setting as yours, and unity tells me that the type or namespace name 'playerActionControls' could not be found.. help?
Make sure the class and file name matches exactly, if you generated the script try regenerating it again. Your class names should be camel case, PlayerActionControls, and you can name your variable after it: private PlayerActionControls playerActionControls;
@@samyam still happens, if it helps im using unity 2019.4.17 and unity hub 2.4.2 it may be different from what you are teaching, but other than that i'm confused and may just give up or restart
Make sure you put serializefield, and if they don’t appear put it on each of them [SerializeField] private float jump; [SerializeField] private float speed; also make sure your script doesn’t have errors Window>General>Console will tell you if you have errors
If you have problems jumping, check if you set the layer mask correctly, the jumpspeed isn't 0, and that the Jump function is getting called.
You can also try this jump function instead:
private bool IsGrounded() {
Vector2 feetPos = transform.position;
feetPos.y -= col.bounds.extents.y;
return Physics2D.OverlapCircle(feetPos, .1f, ground);
}
Which is similar to the other but uses a different Physics2D function.
If there is an issue with spamming the spacebar then here's the fix, just pass in the float value in to the Jump Function and then in jump check if that value equals 1:
playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue());
...
private void Jump(float val){
if (val == 1 && IsGrounded()) {
...
It seems that isgrounded is returning true even after you are not technically grounded. Try changing the radius of the Overlap Circle and make it smaller.
Why you dont just use collisions if character collided then turn boolean?its much easier then calculatin player boundaries?
It is easier to implement but using colliders like that is not always super accurate that's why a lot of platformers use raycasts (that's a whole topic though). Here we are making a function to extend from the boundaries of the collider to make sure it's touching the floor.
@@samyam I can't find player controller I found character controller it is different from player controller
@@samyam how do i change the radius of the overlap circle
I checked and tried so many tutorials about the new input system and got confused more until I saw this one. I understand perfectly and working perfectly on my own project, Thanks a lot! ** YOU ARE SO TALENTED**
Thank you! 😄
For those who have problems spamming the jump key, when we assign the "Ground" layer in the "PlayerController" script, we must unassign the "Default" layer, since if not, both are marked and it always detects a collision in the function " IsGrounded () "
Greetings!
In my pinned comment to this video I also have a fix for spamming the jump key which is a one line addition to the code if you continue having issues 🙂
better communication than 99% of tutorials I've had to deal with
Better communication than 100% of the college classes I have taken.
I have a rule I'm making for myself wherein I won't implement any code unless I fully understand it and you provided A LOT of things to break down. Thanks again!
You just took something really difficult and made it easy. Been seeing a lot of stuff, from unity and a bunch of other sources, saying to use "InputAction.CallbackContext" but it always returned an error for me. I didnt even know I needed to generate a script from the input system, I thought it was some type of global value stored somewhere. Thanks!
inorite! I had no idea you had to explicitly generate the script with the check box on the asset in the project view before anything was hooked up. I was pulling my hair out trying to figure out why my input events weren't making to the associated script until this video.
This was great! I've been searching for a while to find a more recent video to make a good player controller, but most are from years ago and are pretty much obsolete now. These two videos helped me immensely. I did find one issue. If the player presses space to jump but holds it down, letting go of space has the player jump again.
Glad you liked it! That's my bad, it's because the Jump method gets called whether you are pressing down or up on the key.
Here's the fix, just pass in the float value and then in jump check if that value equals 1:
playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue());
...
private void Jump(float val){
if (val == 1 && IsGrounded()) {
...
A year too late, buuut just in case someone wonders the same issue, change Action type to Button rather than Pass Through on the PlayerControls input aciton
In case someone else out there is NOT working with a tile map and cannot get the Jump function to work with the 'ground' layer this is what i did that worked. I am working with an empty gameObject with a 2d box collider as my floor whose Layermask is set to "ground". Only way i got the Jump portion of code to work was to change col =GetComponent();
I then placed a 2Dcircle collider onto my 'Player' gameObject and set radius to 2 and offset Y axis so the bottom of circle is at feet of my Player sprite (in my case 1.37) hope this helps somebody! And great tutorial btw! Def recommend!
Would love it there was a part 2 in the name. Very useful videos
This is actually part of a series if you are interested ua-cam.com/play/PLKUARkaoYQT178f_Y3wcSIFiViW8vixL4.html
It also helps to remember space bar is the jump key. Really great tutorials though. They've really helped me learn Unity and understand certain things I did in my college game math and physics class that I didn't get at the time despite passing the class lol
I am running into one bug with this script, the jump functions occurs on both the press and release of the jump key when in contact with the ground. But this is a VERY nice and straight forward tutorial. Clear, concise and not too much hand waving of details that most tutorials have. Thank you!
Thanks! I included the fix in the pinned comment of mine for this video 🙂
@@samyam I saw that right after I finished the reply :P
Was typing a question and figured out the solution. still best tutorials on the new system i could find thank you!
Great videos! I decided to revisit the new Input system since I'm using Unity 2020 now. I feel like a lot of people made videos about the system a year ago but never revisited it. Also, I seem to recall that making use of the system was much more manual (I don't remember the tutorials I went through having the C# code generated - not sure if that was just them trying to do things very customized or if that feature wasn't implemented at that time). Anyway, you explained the material well, your steps were easy to follow, and now I feel like I know exactly what is different between the legacy and new systems, and no longer feel like the new system is overwhelming and cumbersome! Keep up the great work!
Thank you! The new input system is pretty powerful. Glad you liked the video :)
Finally after two days of trying out a lot of different tutorials of youtube and unity the last 2 days i can use the new input system thanks to you. will stick to your videos now to make the base functions of my game =)
Unity did not provide good videos for the new input system and i couldnt find their own controller script -.-^^
What is the deal with this new input system. I'm super new to learning Unity and I can't get any damn traction with this new input system.
Thanks awesome video . I'm using the rigid body component to move my player, for people who wondering why their player not moving they should replace the movment.y = input.GetAxis("Vertical"); to movement.y = controls.Gameplay.Move.ReadValue(); so it takes the new input. In my case I want to move my player vertically so I used the y axis.
Thank you very much.The reason I wanted to try out the Input System is because Input.GetButtonDown isn't always responsive while running and it was really frustrating,now the jump movement works perfectly fine,thank you very much.I just have a small suggestion for you,instead of using if (IsGrounded) you could just use if (collider.IsTouchingLayers(ground)),which makes it more easy to remember and understand.
Thanks for the input!
after watching some other videos on the new input system and not being able to make it work, I found the previous and this video and you saved me a massive headache. Everything was well explained and everything worked well, thank you so so much! I subscribed and will be using your videos in the future to keep learning :)
Awesome!! Glad it helped 👏
LOL okay so I followed everything relaly well a nd totally broke down right around minute 14:00... I was like OMG I'm not understanding where things are getting referenced anymore! Haha I'm sure if I watch it over and over and google around I will figure it out however when you said, "If this seems complicated, it's because it is," you were right!
i broke down at minute 4:33
Let me know if there's anything I can do to help! We also have a Discord channel discord.gg/SwCKB3Q
Thanks great tutorial series please do more tutorials
Thank you!!
Great tutorial in running through the (new) input system. I'd love to see something more complex like when you want an action (eg. boost) that only works when you're *holding* a button. Regardless, thanks for taking the time to explain it to a beginner.
Sure! I have a hold feature that I cover in my Line Rider series (Make Line Rider in Unity Pt.1 - Input System Manager
ua-cam.com/video/Y1BQoAmTC2s/v-deo.html). There is also a Hold interaction you can add to your actions, where it will only be performed if it is held down after a certain period of time. However if you want to continue to execute something while it's being held down you need to store a variable that's set true when you start pressing and false when you stop
Really nice video, I´m learning the new input system so this help a lot
Hi, Thank you so much for posting this video. I had to convert a project to the new input system and you helped me a lot!
We have a winner here! Simple and Clear to understand.
Regarding the IsGrounded function, couldn't we simply use an
rigidBoby.velocity.y == 0f check instead?
You possibly can, it might be a bit inaccurate, especially for slopes if the player is sliding down (although not fast) the velocity wouldn't be 0.
a really good tutorial! up to date, good to understand, with the explanations and iamges!
This is lovely work honestly been trying to learn more on how to use the Input system with 2D. Only issue I came in with is the "Spam" space button deal. I would be lying if I didn't get a chuckle signing the "you can fly" part from Peter pan when I'm trying everything thing I know and what you recommend.
Check the pinned comment on this video, I put the solution there!
@@samyam Well after I put into it was most likely a sprite issue Idk I was using sprite or it was the just I did the ground wrong either way it's fixed.
@samyam idk but try using 2D sprites might recreate the spam jump deal I was seeing.
Great video! Thank you for using the new input controller too, I was wondering how that worked. How would you go about adding gravity to the player at the apex of the jump to make it less floaty?
since anything that needs to be applied to a rigidbody should happen in FixedUpdate how do we do with this jump function ?
I was looking for something more up to date too! Thanks!
Best Best Best !!!! Thank you for another video too
Oh, one more thing. Rather than have the move function in the Update() method which can cause jitter when the collider boxes of the player and env walls make contact, ppl should instead use the FixedUpdate() method. This removes the jitter.
Also, I am curious why you used Vector3 instead of Vector2?
Thanks again for making this! Was super helpful and I've already learned a TON from this jumping off point.
For those that want details, Update() updates on each rendered frame, while FixedUpdate() updates based on the physics calculation in Unity, so Update() can can slow or speed up based on how intensive you graphics are while FixedUpdate() keeps all your physics calculations in sync. If you put physics based code to update via the Update() method you can get strange physical behavior like jitters in transforms and what not.
stackoverflow.com/questions/34447682/what-is-the-difference-between-update-fixedupdate-in-unity
You should do only physics related calculations/movement in fixed update, instead you can try selecting Interpolate in the Rigidbody component so it smoothly changes position
The input system had been baffling me for too long! Thank you so much for this tutorial! I think the method you used for ground check just might make it easier for me to add a wall jump ability. If I add a similar function for wall check, do you think I can read which side of the player the wall is on and jump from there? How would I go about that?
I would recommend using raycasts instead for detecting both wall and ground, basically shoot out some rays sideways and downwards (the ray will be small 0.1f or similar distance) on every frame and store the collision.
Great Tutorial, really. Just a question, I dont have the "Player Controller" for the cube.
I mean, I have not the Player Controller Component
It doesn’t appear as a component? Maybe you have an error on the script
Check
Window>General>Console
Perfect thanks you a lot! I solve that
Hey, thanks for this tutorial! I was looking at Brackeys' video before this, and it was helpful, but I felt like I couldn't translate what I learned there into a 2D game very well. This helped tremendously!
Glad it helped!
Thanks SOOOO much for the video!! I also need to make a local multiplayer version. are you able to make a video showing that?
None of the other videos I can find seem to work and combining your teaching with someone else's multiplayer videos is just confusing me no end!
I hope you can help cause you're extremely good at teaching!!!!!!!!!!! :)
Thank you!! Yes I have a video on local multiplayer here
ua-cam.com/video/g_s0y5yFxYg/v-deo.html
@@samyam oh you are AMAZING!!! and thanks for the super quick replay. I'm so glad I found you!! :)
Nice tutorial, didn't fully understand how it all works but i'm okay with that, by the way, how can I get those text colors on vs
Godot theme extension (vs code) 🙂. What didn't you understand?
as a programer myself the jumpspeednsounds just silly maybe jumppower, jumpstrengh, jumpforce but jumpspeed mean to me how quickly player lands than jumps so its just kinda wrong great tutorial ☺ tho 👍
Thanks for this video. Helped me a lot.
Did I miss a step for preventing the player character from falling off the end of the ground if I move too far to the left. I created the TileMap collider which I use to only allow jumping when on the ground, but if I move too far to the left, I fall off the platform. Do you have a recommend technique for preventing movement beyond the end of the ground?
Thank you very much for this tutorial, it really really helped! aside a funny thing where it launches me into space if i spam the jump key, it works great! i'm not sure if this is a dumb question though, but how would you handle crouching?
Glad you enjoyed! Make sure the isgrounded function, player collider, and layermask is correct, should only be able to press jump when on the ground. For crouching you will need a crouching animation and you would just decrease the size of the player collider when crouching so it can pass under objects (and then set it back).
@@samyam Gotcha, thank you so much!
Thanks for this! Very clear explanation. Dumb Question: Is there a way to assign a bool to a var like with the old system Ej:
jumpPressed = Input.GetButtonDown("Jump");
Glad you enjoyed the video! With the input system it calls a function whenever it's executed, as we did with the Jump, so you could set the boolean in the function itself if you needed to. There's other callbacks for actions such as started and canceled where you can set the boolean to true or false or do some other effects.
Also if the value is a float with the value one or zero, in the function you can just set the value to a boolean since 1 = true and 0 = false. Convert.ToBoolean is a C# function you can also use to convert an integer to boolean too.
Let me know if that helps!
Thank you very much. it's really helpful.
Legend! Great tutorial.
at 9:54 i have an alternative method for the same thing!
at the time stamped place
IsGround = Physics.CheckSphere(findGround.position, groundRadius, groundMask);
into the Updates first line
then have 3 small things at the top;
public LayerMask groundMask;
public float groundRadius
public Transform findGround;
then then the () away from the IsGround bool
if (IsGrounded)
{
rb.AddForce...
}
thank you tho for the intro to the input system!!
Great tutorial! I’m not sure if this is a dumb question, but how would you add animations and how would you add in more complex movement such as a dash?
No such thing as dumb questions
I have these two videos that might help
How to Set Up an Animator Controller with Sprite Sheets - Unity Tutorial
ua-cam.com/video/1Ll1fy2EehU/v-deo.html
Animator Controller Scripting - Unity Tutorial
ua-cam.com/video/3Ad1wr3qBRw/v-deo.html
As for a dash you can listen for the dash button and add force to the player in that direction (or you can lerp to a location over a certain duration (i recommend a coroutine for this but it can be done in update)) Here’s a simple example blackthornprod made ua-cam.com/video/w4YV8s9Wi3w/v-deo.html
Hi! I have a question: if you wanted to execute what's inside "Jump" in a FixedUpdate manner how would you do it?
"The reason this looks complicated is because... it is..." made me laugh hard
great tutorial having fun following along
Thanks! :D Yeah, I couldn't sugarcoat this one 😂
@@samyam edit: got it working
feel like its often something so simple t.t
Thank you so much! I really learned a lot from this! But could you please do one for 3d movement also? :D
I have a similar video for 3D movement but it uses joysticks, you can easily remove the joystick however
Mobile Joystick with NEW Input System and Cinemachine - Unity 2020 Tutorial
@@samyam oh, okay thanks! I'll watch that! Thanks again for your help! Much appreciated :)
These 2 videos just made almost a thousand Unity videos obsolete.
Samyam, love your tutorials on the new input system. Question for you, do you know how to resolve actions performing twice? If you press jump and hold down the button till your player hits the ground. On release of the button the player will jump again. I discovered this issue when creating a shoot function following your other tutorial. I can't seem to find a way to make the button only function once.
Hi Qlawen, did you try my suggestion on the pinned comment to this video? I added a fix for that there:
```
If there is an issue with spamming the spacebar then here's the fix, just pass in the float value in to the Jump Function and then in jump check if that value equals 1:
playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue());
...
private void Jump(float val){
if (val == 1 && IsGrounded()) {
```
Thank you, thank you, thank you.
couldn't find ANY documentation about applying vector forces / getting the transform using the new input system online. Was searching for DAYS. How did you find this information?? Do you have access to some top secret Unity development bunker?
I wish I did, would make my life easier 😂
Great video! I'm working on a top-down 2d game, and I want to implement a shooting mechanic. In the old input system it was very easy, but I can't make it work with the new one. Please help me!
I actually have a video just for that! ua-cam.com/video/H2RLv0aWUB0/v-deo.html
I have an error in unity that says Assets\Scripts\PlayerController.cs(34,6): error CS1519: Invalid token '-' in class, struct, or interface member declaration
What should I do. It wont show the jumppower or movespeed in unity.
You can double click the error and it will take you to the line where the error is, it seems you have a syntax error on that line (misspelled something)
YOU ARE AMAZING!!!
Hi samyan! When i jump next to a wall i get infinite impulse. How can I fix it? The map on my project is tile based and have a tilemap collider 2D and a composite collider 2D.
Thx in advance!
I found that the walls were layered as 'ground' so that could be the problem.
I created new 'wall' tiles but I can't jump from them.
Hmm so you want to wall jump? What do you mean by infinite impulse?
@@samyam Sorry english isn't my native language.
I uploaded a video where you can see the normal jump and the jump when I'm close to a wall. That's what I mean with infinite impulse.
ua-cam.com/video/S487V8uwCqA/v-deo.html
The video is private so I can’t see it 😵 You can make it unlisted instead and it would work.
do you have a video about how to youse a jump multiplayer with the new input system or is it the sama as before
What do you mean by jump multiplayer (do you mean like a double jump or adding in a speed)? You can do those through code in the update function, just with a different input type.
Thanks for the great tutorial but I am having an issue with the jumping. My character won't jump when standing normally, but if I push my character up against a wall it will jump. I'm wondering if maybe there is a way to expand the square used for checking if it is grounded down further than the box collider?
Yes you can add an offset to the bottomright.y like so:
bottomright.y -= (col.bounds.extents.y + 0.1f)
@@samyam Thanks so much for the help. While playing around with it some more I discovered that for whatever reason if the top of the box collider is bellow the middle of the character the ground check glitches out and doesn't work.
Is there a way to simulate the weight of keys like the old system with button weights?
What do you mean weights? Like a priority? You could possible write a custom component docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/ActionBindings.html#writing-custom-composites
Can you do this same series with visual scripting i mean bolt ??😶😶😶
The tutorial video's are a great help but I ran into an error and dont know what to do about it
I have only done the moving sideways part so far.
I did the exact same things like in the video but my Unity keeps giving me an error message
:Assets\Scripts\PlayerController.cs(35,61): error CS1061: 'InputAction' does not contain a definition for 'Readvalue' and no accessible extension method 'Readvalue' accepting a first argument of type 'InputAction' could be found (are you missing a using directive or an assembly reference?)
I've remade it trice but I get the same result every time
Make sure you are accessing your controls and action correctly, it seems like you are using the wrong names. General syntax is like this ...ReadValue()
@@samyam Thank you
It works now
Thank you (once again).
I can't find player controller are you find it bro
@@sujithkumar4849 Have you downloaded the Input System package?
@@Kromahtique yes I found character controller but it different from player controller
We have to make the player controller script, right click > create c# script, then attach it to our player
Thanks!
thank you for this tutorial miss i've enjoyed it as much as it helped me but can you please teach us how to flip the player when it's moving? :) (i hope this doesn't sound rude or anything it's just english is my second language)
Thanks for watching! This video is actually part of a mini-series and I cover that in a video later on, specifically the Animator Controller Scripting Video ua-cam.com/play/PLKUARkaoYQT178f_Y3wcSIFiViW8vixL4.html
Hi,
Thank much for this tuto.
M. D.
I've been following this tutorial, it was going fine untill i got "error CS1585: Member modifier 'private' must precede the member type and name" on line 12 "private PlayControls playcontrols;" do you know how to fix this? if so please tell me. thx
Great tutorial - but where have I messed up? My player only jumps when their layer is set to ground, and then naturally jumps like flappy bird in mid air as if they are always in contact with ground. All layers are in the right order and the player collider does not overlap. Have tried every combination with alternating layers turned off an on. I have done this to render it impossible for the player collider to be in contact with anything while in the air. Yet the input still has the player 'jumping' while in mid air. All code correct and accounted for as directed in the video. have tried below solutions but to no effect.
Did you check the player collider size? Maybe it’s too big and that’s why it still thinks it’s grounded
Thanks for your work! I have a question for you: I am using a Plugin from the asset store that uses the old input system (Pixelcrushers Dialogue System). In the Project Settings I've set "Active Input Handling" to "Both" so I can use the plugin AND the new input system. Do you know if this has any impact on performance? Would you do it like this, too, or rather stick to one input system? (In my case this would mean to switch back to the old one. My game has very simple controls, so complexity wouldn't be an issue. I just prefer the new input system bc it seems so much easier and straigth forward to use)
That asset supports the new input system :)! ua-cam.com/video/iUoD0eDZPWw/v-deo.html
I rather stick to one if possible, but if an asset must use the old one then there is no way around it. But I'd still use the new one to do the main input mechanics (so switching to Both).
@@samyam Thanks for your reply! Oh, damn, it totally didn't occur to me to even check whether the asset supports the new input system because i had already got so used to it using the old system *facepalm* Double thanks for answering an actually stupid question ;)
No question is stupid! No worries :)
So my problem is that the player partly merges into a wall when he walks into it (even midair), and this gives the player an opportunity to jump again. Any help is much appreciated!
edit: just being too close to a wall makes the player able to jump as well.
You can try putting different colliders on the walls that aren't marked as ground, you can also try giving the wall a physics material with no friction, or you can try doing raycasts for collision instead and shoot raycasts under your player to see if they are grounded
@@samyam thanks! I will try that.
Quick note: I thought this bug was interesting since you can hop up walls so I decided to make the player bouncy and keep it. I will not keep it in my future projects though.
Please do one with Gamepad and Keyboard, also can they be used together? Hot swapping maybe?
Yeah, the input system detects where the inputs are coming from and switches automatically, just make sure the action type is not set to Passthrough. At the top left you can add a controller scheme. I'll look into making a video on this.
@@samyam I'd be very thankful, i'm having a lot of trouble using the new system and there aren't much up to date tutorials about it especially on how to use stuff like accelerometer, gamepad.
@@MuhammadAli22931 ua-cam.com/video/f0wax8LufqQ/v-deo.html
ty homie :)
Would you consider using a vector 2 since it's in 2d to save memory space when exporting to a phone or something?
I'm not sure what Vector3 you are referencing, do you mean movement? All transform properties are Vector3 in Unity.
Does anyone know how to fix not being able to edit speed/jumpspeed in the Player Controller (Script) component?
Add a serialize field to it
[SerializeField]
private float speed = 10f;
@@samyam Hey just seeing this now, but I fixed it! I realized I had forgot to save, so it never carried over into the Inspector
First off, nice vid. Secondly when i add the first new component to my player to add the player controller script component it doesnt allow me to put in anything. It just says what script im using. It did work first but when i removed the component then added it again the problem happened. Do you know what wrong?
Also i triple checked your script and couldn't find anything wrong. I have serialize field and all that.
I just found this error message if it helps: Assets\Scripts\PlayerController.cs(12,9): error CS0246: The type or namespace name 'Void' could not be found (are you missing a using directive or an assembly reference?)
Hi Jesse, you won't be able to add the script to the game object if there is an error on it. In the console window on Unity (Window->General->Console) could you double click the error and paste here the code you are talking about? You might have accidentally changed something on that line.
samyam ok I will try hold on.
I have three errors i think i will post them all here. I dont understand what they mean.
I followed all the steps but when it comes to the cube and you have to add the player controller its doesn't pop up even tho I have the c#script right there any advice
That means you have an error in your script, check the Console (Window->General->Console)
I also have a Discord channel if you have any further questions and would like to join discord.gg/B9bjMxj
Hey there anyone who sees this, I have an interesting situation that I am trying to solve:
I'm trying to create a simple switch in my game. The idea is that when the player is touching the switch, and they press the a button it will open a door, and possibly do other actions down the line.
Trouble is, I cant seem to use both the button press and collision both as conditions at once. The main reason its not working for me (as far as I can tell) is that I cant seem to place the button pressed into an if statement.
Ideally, I would like it to work something like this.
If(Player collides with something && A button is pressed){
Do something.
}
So basically, what can I use within the new input system to determine if the player has pressed the A button, in the context of an if statement?
In the old Input Manager we can set the gravity and sensitivity so that button presses return a float between -1 and 1. In the new Input system, using the 1D axis only seems to output 0, the min value or max value. Is there a way to recreate this in the new input system?
According to the documentation the Axis Composite should return the values “This means that if the buttons are actual axes (e.g. the triggers on gamepads), then the values correspond to how much the axis is actuated.” They also have an Evaluate Magnitude method that returns the current magnitude, which is probably what you are looking for. docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.Composites.AxisComposite.html
@@samyam Thanks for replying and sharing the doc. After more reading up on it I found that what I'm looking for is sensitivity (digital input get smoothly increased to its max value (of 1)) and gravity (digital input gets decreased continuously to 0 after releasing). I want it to smooth out the movement when using boolean inputs like standard keyboard keys.
There is a solution here but I don't understand it yet so I'm not certain it works: forum.unity.com/threads/so-how-do-i-get-input-getkeydown-a.939347/#post-6138555
I've found that I can recreate this using 'Mathf.MoveTowards' ...
currStrength = Mathf.MoveTowards(currStrength, maxStrength, acceleration * Time.deltaTime)
Where maxStrength is set to the movement input value (-1, 1, 0) on every change.
I then would use currStrength instead of where you have movementInput.
i really dont understand all of it and i just wanted to ask if theres a way to make like: if (input){blabla}
Yes in update you can do
If (playerActionControls.Land.Move.ReadValue()!= Vector2.zero) etc...
Basically it's saying if we are moving then do something. The way I'm doing the movement is similar. With the jumping I'm just saying to execute the jump command when we perform our jump action.
@@samyam thanks. also wow youre fast at replying
even if this video was made in mid 2020 and now it is almost 2022, I am completely stuck on this one thing, when putting the player controller on the cube when you type it in it automatically pops up, but for me no such component exists then when trying to add it as one, it just creates a whole new PlayerController script!
You probably have an error in your code, doesn't let you add it until you fix the errors, check the console in Window>General>Console
You're so good in explanation. :) Could you please do this in 3D?
Thanks! I have a third person controller
ua-cam.com/video/ImuCx_XVaEQ/v-deo.html
and first person here
ua-cam.com/video/5n_hmqHdijM/v-deo.html
Yes, I know the 3rd Person tutorial. But I can't add the component which you add to convert the cinemachine for the new Input System. I don't know why. Perhaps because I still work with the 2019.4 version. I am installing the 2020 LTS right now and will try it again. Thanks for the response. 😊
It should work with 2019.4! Make sure you have updated input system and cinemachine versions :)
@@samyam The new Unity is installed and voilà I can add Cinemachine Input Provider now! 😃 I will start your tutorial again. 🥳
It finally works.
samyam I've been using Unity off and on for years and if there's one thing that's stuck with me more than others, it's that moving objects through their transform when they need to interact with the physics system is just bad form and asking for trouble. Like the object not responding to collisions properly.
The only reason I can think of that it might be ok to move an object with transform rather than a rigidbody is if that object doesn't need to interact with the physics system. So why teach people this way instead of rb.velocity or rb.position?
In an actual game (platformer), I recommend using custom physics and moving with Translate/position rather than rigidbodies at all. However this meant as a beginner video and that would take a whole series to go through (Sebastian Lague's 2D Character Controller).
I do agree that using transform position while also having a Rigidbody does cost more performance and can lead to unstable collisions since the rigidbody calculation is done after the transform position changed. According to Unity documentation, Rb velocity is more useful for changing the velocity like when jumping and not really meant to be changed every frame. The rb position is also meant to be used to move instantaneously to one location.
@@samyam Thanks for taking the time to get back to me and I appreciate the thorough response. I'm just recently getting back into Unity after a while away, which is how I came across your channel, and looking through beginner videos has been helping me to relearn things I've forgotten and learn things I missed before.
I'll keep in mind what you said and look into Sebastian's videos also. Thanks and take care!
Glad you like the content. Feel free to join my discord channel if you have any questions: discord.gg/B9bjMxj
why not ?
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * Time.deltaTime * horizontalInput * speed);
is there any performance different ?
I'm using the new input system for this video, I have a video here explaining why I use the new system
ua-cam.com/video/GyKBoDF_Oxo/v-deo.html
@@samyam ok i will check it ,i love your content by the way
How could this be changed so that the character can go up and down on a map while still also being able to jump? Mind you I have no idea how maths work--and I tried rejiggering the code so that the inputs became Vector2 and 2D vectors...my character (i'm still figuring out how to move across a tile map or whatever) could go back and forth on the collider i'd set up (just the plain green box) and they could jump and ostensibly move up and down (if i froze the y axis they could move....wait I just answered my own question....you can't have Y upmovement and a jump feature at the same time...or can you!? (also it made it so the animations stopped working except for idle and jump....I don't know if i'm making sense.
Not sure I understand 😅 I have a video on top down movement but I don't think that's what you are looking for. Do you mean like freezing in the middle of a jump?
ua-cam.com/video/H2RLv0aWUB0/v-deo.html
So I set everything up and used the ctx trick in the pinned comment, but I have some platforms with my ground layer, and if you just spam spacewhile directly in contact with the side of the platform you can get HELLA extra height. How do I stop this from happening?
In that case you might want to use a raycast 2d and shoot a ray downward from the player to check if the ground is there (it's another way to do ground check). Most people have multiple raycasts (3, two on the ends and on on the middle) for better detection of the ground especially if you are on an edge).
Here's an example kylewbanks.com/blog/unity-2d-checking-if-a-character-or-object-is-on-the-ground-using-raycasts
Their distance is pretty large in the example, might want to reduce that to maybe 0.1f.
samyam Thanks! I’ll try it out when I get a chance.
samyam I got it working with the ray casting and a few tweaks in my code. Thanks.
Hello your tutorial was pretty useful but I won't a fps controller with the new input system can you make a tutorial about that please
Thanks for watching! Right now I'm working on completing this series but I'll take into account your suggestion for future videos. 👍
@@samyam ok thanks
Hi, I am trying to setup a multi-profile input system. In which based off the binding options the user selects, the game will use it to match to one of the preset input profiles. My issue is in the line where you pass the performed jump into the jump function. It is setup where you have to choose a single profile ("Land" for example), but that doesn't work if a different input profile is being used. I tried to insert some sort of string variable to make the profile dynamic but I just don't know what to do based on how the syntax messes up functions like .ToString()
If you mean switching the action maps you can do something like this: player_input.SwitchCurrentActionMap(player_input.actions.GetActionMap("Player").id);
When the player selects a profile you can store the map string associated with it and then pass it to the SwitchCurrentActionMap function.
@@samyam that works however doesn’t solve the syntax issue with character controller script. Jump is done using “PlayerControls.Profile.Action.Performed” and the “profile” part of it is static. So if I switched input profiles it wouldn’t work anymore and I’m not sure how to solve it. I tried using a variable for the profile name and couldn’t figure it out
I see, try using the PlayerInput component where you can switch out the active action map but keep the code the same.
playerInput.actions[“Move”].ReadValue()
@@samyam ok thank you! If that doesn’t work my other idea was to just add a bunch of listeners with all the different combinations and then for the composite movement I would just add all the listeners together into the single movement variable if that makes sense.
Also thank you for these tutorials this is the only one I was able to actually understand what the code meant and how to apply it :)
hello samyam i have a problem i try to solve it over 8h now but idk, i make step for step and it works so i can move but i get everytime i press the "A" or "D" key this error "InvalidOperationException: Cannot read value of type 'Vector2' from composite 'UnityEngine.InputSystem.Composites.AxisComposite' bound to action 'Land/Move[/Keyboard/a,/Keyboard/d]' (composite is a 'Int32' with value type 'float')" i hope u can help or somebody else?
i cant get the player controller script to the component i did exactly as you said i followed everything thoroughly but it didnt work PLEASE HELP 😳
Are there are errors? Check Window>General>Console and make sure there are no errors. You can also put Debug statements ua-cam.com/video/vy7WXLArj4U/v-deo.html
or breakpoints to find bugs or errors in your code.
@@samyam but i didnt find anything
There are no errors? You can also ask in our help chat on the discord channel discord.gg/bvQEGk7
I think I'm missing something. I tried adding the "[SerializeField] private float speed, jumpSpeed;" but when I add the PlayerController comment to the cube, I don't see "speed" or "jumpSpeed". Can anyone help? Do I have to do something to MS Visual Studio?
You have to have a SerializeField separate per variable.
[SerializeField]
private float speed;
[SerializeField]
private float jumpSpeed;
Let me know if that helps.
Thank you, mam, it is a great series just a small help my code is correct in fact everything is as you stated still my character doesn't jump. Please help mam
I have pinned a comment to this video regarding this issue, check it out and let me know if those work. Make sure the layermask is correct, jumpspeed is not 0, and that the jump function is getting called.
@@samyam thanks a lot mam it worked for me 😊
InvalidOperationException: Cannot read value of type 'Single' from composite 'UnityEngine.InputSystem.Composites.Vector2Composite' bound to action 'Land/Movement[/Keyboard/w,/Keyboard/s,/Keyboard/a,/Keyboard/d]' (composite is a 'Int32' with value type 'Vector2')
How are you reading the value?
heyy when you are typing something in the Visual Code Editor ,how do you get suggestions bcoz i was not getting some suggestions while I was typing.
Also my Player Controller script doesnt work means I don't get the option of changing speed and jump but i have followed every step of yours. :(
I have a video on setting up visual code with suggestions ua-cam.com/video/4WWX2_tZu5Q/v-deo.html
If you mean you can’t see the speeds in the inspector, make sure you put a SerializeField on both of them. Also make sure to check the Console (Window>General>Console) for any errors in your script
@@samyam sorry for irritating you but I now realized that when I click play it says that compiler errors must be fixed
So what could be the reason for that?
Sorry again for taking your valuable time🙏😕
@@samyam also thank you for your super fast replies😅
No problem! It means you have errors on your script that you have to fix (Window>General>Console)
You can double click the error and it will take you to the line where the error is. And the description of the error usually helps in solving the problem. I have a video on console and debugging that might help ua-cam.com/video/vy7WXLArj4U/v-deo.html
@@samyam OK I will watch your other videos and will figure it out myself 🙏🙏thanks a lot again your videos seem really easy to understand 🙌
hello thanks for great tutorial i have some issue everthing works until jump
unity give me error
Assets\Scripts\PlayerController.cs(40,8): error CS0103: The name 'Phsics2D' does not exist in the current context
definition for ground
[SerializeField]private LayerMask ground;
return Phsics2D.OverlapArea(topLeftPoint,bottomRightPoint,ground);
same as you do far as i can follow the tutorial
can you give me little guidence what can cause this becuse everthing looks correct to me
You spelled physics wrong, it is Physics2D
@@samyam you're life saver thanks a lot. english isnt my main language i didnt noticed
my character does not jump anymore i was adding an idle animation and while doing that everything broke, my colliders and ground, ceiling checks had all been moved up and i could no longer jump, do you know what the problem is?, it doesnt say theres any errors in the code so im really lost on this one
Hard to tell without seeing the project, try setting the player on a simple cube with a collider and trying to debug from there
I have a video how to debug log here ua-cam.com/video/vy7WXLArj4U/v-deo.html
Also setting breakpoints would help walk you through the code. Make sure you also have the layer for Ground set correctly
@@samyam Thanks I will try that tommorow!
Welp my character jumps but only when a platform is above him not under him lol. I tried changing the Vector2 +=/-= lines (lines 40-46) to match each other, reverse of what you wrote or any other combinations but nothing :/. Im assuming that might be the culprit but any help would be really appreciated!
Maybe it’s because the overlap area it’s checking isn’t on the player correctly. You can paste the portion of the code here so I can take a look, you can also try using another function to detect collisions
docs.unity3d.com/ScriptReference/Physics2D.OverlapBoxNonAlloc.html
@@samyam Thank you a lot for getting back to me so quick. Lol now I don't have to wait weeks before hearing a response like other youtubers. Def just earned yourself a new subscriber! But I noticed that if my box collider is ridiculously large on the y size (about 3 times my character's height) it works normally as intended but trying to bring it down to my character's actual height and nothing :/. Here is my code for lines 46-58:
private bool IsGrounded()
{
//Positions for Grounded Collider
Vector2 topLeftPoint = transform.position;
topLeftPoint.x -= col.bounds.extents.x;
topLeftPoint.y += col.bounds.extents.y;
Vector2 bottomRightPoint = transform.position;
bottomRightPoint.x += col.bounds.extents.x;
bottomRightPoint.y -= col.bounds.extents.y;
return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
}
Ah ok I think I figured out the issue. The box for my rect tool is a lot larger than my object so anytime the collider is outside that box than it will allow me to jump. Do you happen to know how to shrink that resize rect tool box (lol the one with blue dots at the corners) back down or in line with my actual image/object? Sorry if thats confusing lol
In the inspector for that component you can press Edit on the collider to change the bounds of the collider to more fit your character
@@samyam its something with actual rect box for the sprite. Lol sorry could've said its a sprite imported from Aseprite but I found out the issue. Its using the whole area of the canvas instead of just cropping down to what is drawn. But what you said also made my life a lot easier! Thank you again!
hello i tried using your tutorials and i wondered if you know why it says that "playerActionControls" is not found in the global namespace? can you help me :D
it may actually be because i am using unity 2019. maybe i should change :D
That’s the variable we declare at the top of the class for our controls, maybe you forgot to declare it?
private PlayerActionControls playerActionControls;
@@samyam i am really sorry for taking up your time but i am really sure that i did declare it i just added my code here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
private PlayerActionControls playerActionControls;
[SerializeField] private float speed, jumpSpeed;
private void Awake()
{
global::playerActionControls = new PlayerActionControls();
}
private void OnEnable()
{
playerActionControls.Enable();
}
private void OnDisable()
{
playerActionControls.Disable();
}
void Start()
{
}
void Update()
{
float movementInput = playerActionControls.Land.Move.ReadValue();
Vector3 currentPosition = transform.position;
currentPosition.x += movementInput * speed * Time.deltaTime;
transform.position = currentPosition;
}
}
i found the problem ty for the help
@@ludvigstorm3972 what was it I have the same issue?
error CS0246: The Type or namespace “PlayerActionControls” could not be found (are you missing a using directive or and assembly reference?)
shows that error when I finish the coding part. Any help?
Try regenerating the input script from the input action asset and make sure the spelling is correct
@@samyam thanks!
Click on your action asset you created and in the inspector you can Generate C# Script (by unchecking and checking again)
Is this movement physics based?
The jump is physics based, the movement is not. If you'd like to implement a unity-physics free character controller based on raycasts I recommend Sebastian Lague's Character Controller 2D series.
Unluckily it works with this 3D Box, but not when using a rigged animated character inside a "game objekct" - my character moves sideways but can jump to infinity, with the same settings.... :(
Are you talking about the box collider? If so I use a 2D Box Collider not a 3D one. Make sure the collider is not super big or else it will register on the ground when it's not. I also have some other suggestions in my pinned comment to this video, if you expand it I have a fix for a spamming the spacebar bug.
so i copied everything correctly, or so i thought i did, i got stuck at 4:20 (wow how perfect)
the component does not have the same setting as yours, and unity tells me that the type or namespace name 'playerActionControls' could not be found..
help?
Make sure the class and file name matches exactly, if you generated the script try regenerating it again. Your class names should be camel case, PlayerActionControls, and you can name your variable after it:
private PlayerActionControls playerActionControls;
@@samyam still happens, if it helps im using unity 2019.4.17 and unity hub 2.4.2 it may be different from what you are teaching, but other than that i'm confused and may just give up or restart
I came across a problem the speed and jump settings dont aper for me
Make sure you put serializefield, and if they don’t appear put it on each of them
[SerializeField]
private float jump;
[SerializeField]
private float speed;
also make sure your script doesn’t have errors
Window>General>Console will tell you if you have errors