crabcrabcam crabcrabcam - 2 months ago 11
C# Question

How do I stop my character feeling like they're on ice using RigidBody2D Velocity

I am currently using RB2D velocity for movement but I can't make it stop sliding after I've finished pressing the button. It feels like the Ice level from Mario. How do I stop my character sliding everywhere?

My code is:

void Movement() {

if (Input.GetAxisRaw ("Horizontal") > 0.1) {

GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);

}
if (Input.GetAxisRaw ("Horizontal") < -0.1) {

GetComponent<Rigidbody2D> ().velocity = new Vector2 (-speed, GetComponent<Rigidbody2D> ().velocity.y);

}
if (Input.GetAxisRaw ("Vertical") > 0.5 && grounded) {

GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jumpHeight);

}
}


My speed is set to 5, jumpHeight is 10 and I have both box collider and RigidBody2D on my player

Thanks for any help in advance

Answer

You can use the transform to move the object when pressing keys and directly move it without using the physics.

Also using the velocity, you can set it to 0.0f when you are not pressing any button to stop moving the object.

crabcrabcam is now using:

    void Movement() {

    if (Input.GetAxisRaw ("Horizontal") > 0.1) {

        GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);

    } else if (Input.GetAxisRaw ("Horizontal") < -0.1) {

        GetComponent<Rigidbody2D> ().velocity = new Vector2 (-speed, GetComponent<Rigidbody2D> ().velocity.y);

    } else if (Input.GetAxisRaw("Horizontal") == 0 && grounded) {

        GetComponent<Rigidbody2D> ().velocity = new Vector2 (Vector2.zero, GetComponent<Rigidbody2D> ().velocity.y);

    }


    if (Input.GetAxisRaw ("Vertical") > 0.5 && grounded) {

        GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jumpHeight);

    }

}

This makes it floaty in the air but whilst grounded it stops responsively :)

Comments