- Home /
My Character keeps moving even when i release the key(2D)
I am new to unity and I am having this problem. The character is moving just fine but when I release the input keys, it keeps moving and slowly comes to a stop after 3-4 seconds. Here's my Script.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float moveSpeed;
public float jumpHeight;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
// Use this for initialization
void Start()
{
}
void fixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
}
}
}
Please help!
Comment
Answer by Shameness · Jun 14, 2019 at 05:15 PM
Instead of :
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
try :
transform.position += new Vector3(moveSpeed * Time.deltaTime, 0);
Use Rigidbody2D if you want physics effects. Manipulate transform.position if you want to 'translate' position. Link for further details:
If you're using physics there are ways to slow the character down quicker. For example you can manipulate the drag, or reduce the velocity until it reaches 0 while you are not pressing the input key.
To answer your question, it continues to move because of the residual force on the rigidbody.
Your answer
![](https://koobas.hobune.stream/wayback/20220612203210im_/https://answers.unity.com/themes/thub/images/avi.jpg)