- Home /
Other
Handling friction in scripts for a 2D platformer
I've been working on a new 2D platformer project, as I have been working on one before, but I wanted to neaten up my code and also reinforce the different steps to making other objects. I just wanted some more practice for making 2D games. When creating the character, I had the issue of sticking to walls, which I was able to fix using a separate collider for the feet, and a separate collider for the body. I set the friction of the feet collider to 1, and the body collider to 0. They both have 0 bounciness. With these settings, however, I could not stop moving in midair. When letting go of the a and d keys (which are used to move) when I am jumping, I keep my momentum. Instead, I want my momentum to come to a stop. I tried creating a friction variable in my script, but this caused the player to continually slide, because the friction would keep being applied as long as the x velocity of the rigidbody is higher or lower than 0. With how the physics work, this causes the player to slide. Does anyone have a solution to this problem?
Answer by benjaminfranklineatsfruit · Mar 03, 2021 at 03:40 PM
Try this:
Use one collider, with a material that has no friction/bounce.
Suppose "A" & "D" is your keys to move left and right.
Use this code to "Stop".
private Rigidbody2D rb2d; void Start() { rb2d = gameObject.GetComponent<Rigidbody2D>(); } private void FixedUpdate() { //assuming you use "d" & "a" to move left and right //Stop moving/Skidding if (Input.GetKeyUp("a") || Input.GetKeyUp("d")) { //set the x velocity to 0 rb2d.velocity = new Vector2(0, rb2d.velocity.y); } }