Question by
ShroomWasTaken · Sep 22, 2015 at 11:44 AM ·
c#2d gameplayer movement
2D player movement problems (moving by itself)
So, I have a PlayerMovement script, which has keypresses and all in it. The player moves fine however sometimes when I let a key up the player continues to move automatically.
Here's the code : (if you need anything else just tell me!)
void Update () {
// Speed limiting
if (playerRigid.velocity.x > speedLimit)
{
playerRigid.velocity = new Vector2(speedLimit, playerRigid.velocity.y);
}
if (playerRigid.velocity.x < -speedLimit)
{
playerRigid.velocity = new Vector2(-speedLimit, playerRigid.velocity.y);
}
// Movement Inputs
if (Input.GetKey(KeyCode.D))
{
playerRigid.velocity = new Vector2(speedLimit, playerRigid.velocity.y);
playerRigid.AddForce(Vector3.right * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
playerRigid.velocity = new Vector2(-speedLimit, playerRigid.velocity.y);
playerRigid.AddForce(-Vector3.right * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.W))
{
playerRigid.velocity = new Vector2(playerRigid.velocity.x, speedLimit);
playerRigid.AddForce(Vector3.up * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
playerRigid.velocity = new Vector2(playerRigid.velocity.x, -speedLimit);
playerRigid.AddForce(Vector3.up * speed * Time.deltaTime);
}
// UP PRESSES
if (Input.GetKeyUp(KeyCode.D))
{
playerRigid.velocity = new Vector2(0, playerRigid.velocity.y);
}
if (Input.GetKeyUp(KeyCode.A))
{
playerRigid.velocity = new Vector2(0, playerRigid.velocity.y);
}
if (Input.GetKeyUp(KeyCode.W))
{
playerRigid.velocity = new Vector2(playerRigid.velocity.x, 0);
}
if (Input.GetKeyUp(KeyCode.S))
{
playerRigid.velocity = new Vector2(playerRigid.velocity.x, 0);
}
}
Comment