So I am making a 2D platformer and I am making the movement of the player using AddForce, the problem is that the player slides and the movement isn’t snappy, how do I make a counter force that stops the player instead of sliding?
private void PlayerInput()
{
movementInput = Input.GetAxisRaw("Horizontal");
isjumping = Input.GetButton("Jump");
}
private void Movement()
{
// check if on ground
isGrounded();
// if grounded and have extra jumps then jump
if (isjumping && readyToJump && extraJumpsLeft > 0)
{
Jump();
}
// move player
rb.AddForce(transform.right * movementInput * speed * Time.deltaTime);
}
I know that but the problem is that it slows down the overall movement which I don’t want + I have the friction of the player to 0 so that it doesn’t get stuck on the sides of walls
AddForce is pretty much the opposite of “snappy movement”.
If you need to use a Rigidbody/2D but want snappy movement, set its isKinematic field to true.
A kinematic body basically means it will still react to collisions, but it will not move on its own from external forces - you need to explicitly tell it how to move.
Rather than using AddForce, you would use MovePosition instead, which is pretty much identical to transform.Translate.
This will mean that you would need to calculate your own jumping/falling force logic, however, but a starting point would be something like this:
public class Example : MonoBehaviour {
//isKinematic = true
public Rigidbody2D body;
//Standard Earth gravity force value. Can be changed for stronger/weaker gravity.
public float gravity = -9.81f;
public float jumpStrength = 10f;
private Vector2 movement;
private float currentVerticalForce;
void Update() {
float horizontalMove = Input.GetAxisRaw("Horizontal");
if(IsGrounded()) {
//As long as the player is grounded, there will be no vertical movement.
currentVerticalForce = 0f;
if(Input.GetButtonDown("Jump")) {
//Once the player jumps, set the vertical movement to the initial jumpStrength.
currentVerticalForce = jumpStrength;
}
}
else {
//While the player is not grounded, reduce vertical movement by gravity * delta-time.
currentVerticalForce += gravity * Time.deltaTime;
}
movement = new Vector2(horizontalMove, currentVerticalForce);
}
void FixedUpdate() {
//Use MovePosition to move a kinematic Rigidbody2D.
body.MovePosition(movement);
}
bool IsGrounded() {
//etc...
}
}