Hi guys im making a 2d platformer and im having some trouble with stopping the player from sliding forwards when i stop pressing a key?
heres my movement script if you could help that would be great
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public float jumpForce;
private Rigidbody2D rb2d;
public Animator animator;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void Update()
{
animator.SetFloat("Horizontal", Input.GetAxisRaw("Horizontal")) ;
if (Input.GetKeyDown(KeyCode.Space) && Mathf.Abs(rb2d.velocity.y) < 0.001f)
{
rb2d.AddForce(new Vector2 (0, jumpForce), ForceMode2D.Impulse);
}
}
void FixedUpdate()
{
float moveInput = Input.GetAxisRaw("Horizontal");
if (moveInput > 0 && transform.localScale.x < 0)
{
Flip();
}
else if (moveInput < 0 && transform.localScale.x > 0)
{
Flip();
}
rb2d.AddForce(new Vector2(moveInput * moveSpeed, 0));
}
void Flip()
{
Vector3 currentScale = transform.localScale;
currentScale.x *= -1;
transform.localScale = currentScale;
}
}
You can add a physics material with increased friction to the player’s collider. Eventually you may find it better to have multiple colliders on your player so then you can have a collider at the player’s feet with lots of friction and a collider on the body with no friction.
When you increase friction you’ll need to increase the player’s moveSpeed. You can also decrease the player’s mass to make the player feel lighter and more responsive.
You can decrease the moveSpeed when the player is no longer on the ground. Take a look at other controller scripts to see how to detect the ground. You’ll probably learn lots from seeing how other people do it.
I replicated your problem, and the issue is that when we use the AddForce to move the player, this causes momentum to carry over when the key is released.
Now, I don’t know which option you would like best, but you have a couple based on what you want to accomplish:
Try using velocity-based movements instead of physics-based forces. This will give you control and stop the movement immediately.