(2D) My Character wont stop moving/sliding when I let go of the button
When i press A or D to move left or right my character will keep sliding in the direction i pressed when i let go of the button, as if he was sliding on ice or something. I cant seem to figure out how to make him stop when i let go of the button.
Here is my code:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float moveSpeed;
public float jumpHeight;
public Transform groundcheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
private bool doubleJumped;
// Use this for initialization
void Start () {
}
void FixedUpdate() {
grounded = Physics2D.OverlapCircle(groundcheck.position, groundCheckRadius, whatIsGround);
}
// Update is called once per frame
void Update () {
if (grounded)
doubleJumped = false;
if (Input.GetKeyDown (KeyCode.W) && grounded)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
}
if (Input.GetKeyDown(KeyCode.W) && !doubleJumped && !grounded)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
doubleJumped = true;
}
if (Input.GetKey (KeyCode.D))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKey(KeyCode.A))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
}
}
Answer by OncaLupe · Nov 02, 2015 at 12:55 AM
Check the physics materials on the player and the ground objects, make sure that they aren't set to a very low friction.
Also, you're calling GetComponent multiple times every frame, this is a very inefficient setup as GetComponent is an expensive operation. You should store a reference in Awake/Start and use that.
At top of script: Rigidbody2D myRigidbody2D;
In Awake or Start: myRigidbody2D = GetComponent < Rigidbody2D >();
Then when needed: myRigidbody2D.velocity
Your answer
Follow this Question
Related Questions
How do I fix my FPS controller from sliding? 0 Answers
My 2d movement script isn't working 0 Answers
Why doesnt this code dash I dont see any issues with it 0 Answers
How to make character script work 0 Answers